WordPress.org

Ready to get started?Download WordPress

Forums

WP_Query Filters (3 posts)

  1. Steven Word
    Member
    Posted 3 years ago #

    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)

  2. takien
    Member
    Posted 3 years ago #

    Hello, stevenkword

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

  3. Steven Word
    Member
    Posted 3 years ago #

    @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. :)

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.