Essentially, I'm trying to query using a filter for the args being fed into WP_Query() like so:

    public function filter_wp_query( $args, $template_slug ) {

        $args['post_type']         = 'post';
        $args['search_post_title'] = isset( $args['s'] ) ? $args['s'] : '';

        $args['meta_query'] = [
            'relation' => 'OR',
                'key'   => 'hide_thing',
                'value' => '0'
                'key'     => 'hide_thing',
                'compare' => 'NOT EXISTS'

        add_filter( 'posts_where', function ( $where, &$wp_query ) {
            global $wpdb;
            if ( $search_term = $wp_query->get( 'search_post_title' ) ) {
                $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $wpdb::esc_like( $search_term ) ) . '%\'';

            return $where;
        }, 10, 2 );

        return $args;

This is being applied on the following filter:

$recent_items_args = apply_filters( 'my_template_manager_recent_articles_args', $recent_items_args, $_GET['my-template'] );

Which is being fed into WP_Query like so:

$recent_items_query = new WP_Query( $recent_items_args );

Normally this query (without the 'meta_query') takes no time at all and works perfectly. Additionally, it works great without the 'NOT EXISTS' check. But once I add in the 'relation' => OR along with the NOT EXISTS check, it slows way down -- to the tune of 12-15 seconds.

Is there a different/better way to do this that doesn't involve a huge override of the actual query being performed?

I've considered setting the 'hide_thing' meta value on all posts if there's no quick way to query for 'NOT EXISTS' and that will be my path forward, but I thought I'd ask you fine people to see if there's a way to modify the existing meta query so that it works.

Thanks in advance!

  • 1
    What are the possible values of 'hide_thing'? Can you do a != on that value and thereby get rid of the OR and the NOT EXISTS ? – shanebp May 20 '15 at 21:42
  • Thanks for following up! The possible values (for posts that have the meta value assigned) are 1 or 0, but I want to get the posts that either have it set to 0 or don't have the setting at all. – tdlm May 21 '15 at 22:59
  • Then do a get_col for those post_ids with the value set to 1 and include them in WP_Query using post__not_in – shanebp May 21 '15 at 23:15
  • Hmm.. I'll give that a shot and report back. Thanks! – tdlm May 22 '15 at 16:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.