Support » Plugins » Hacks » WP_Query Filters

  • Steven Word

    (@stevenkword)


    WPEngine Employee

    I can not figure out how to apply a filter to a custom query.

    For example:

    <?php
    wp_reset_query();
    $published_query_string = "author=39&post_status=publish";
    $publishedQuery = new WP_Query( $published_query_string );
    while ( $publishedQuery->have_posts() ) : $publishedQuery->the_post();
    	do_some_stuff();
    endwhile;
    ?>
    <?php
    function filter_where_custom() {
    	$where .= " AND (wpostmeta_type.meta_key = 'foo')
    		AND (wpostmeta_type.meta_value = 'bar')";
    	return $where;
    }
    ?>
    <?php
    add_filter('posts_where', 'filter_where_custom');
    ?>

    This will apply the filter to the standard query, but not to this custom one created with new WP_Query.

    I feel like I may need an apply_filters() hook somewhere… help?

    (sorry for the double post)

Viewing 2 replies - 1 through 2 (of 2 total)
  • Hello, stevenkword

    Place add_filter( 'posts_where', 'filter_where_custom'); just before your custom query.

    Thread Starter Steven Word

    (@stevenkword)

    WPEngine Employee

    @takien

    Thank you for the reply. I was able to get the code working with a small tweak.

    $published_query_string = "author=$user_id&post_status=publish";
    $publishedQuery = new WP_Query();
    add_filter('posts_where', 'filter_where_custom');
    $publishedQuery->query($published_query_string);
    
    while ( $publishedQuery->have_posts() ) : $publishedQuery->the_post();
    	do_some_stuff();
    endwhile;

    Once I realized I was not including the filters on the page I was working with, think started progressing quite a bit faster. 🙂

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘WP_Query Filters’ is closed to new replies.