Apply pre_get_posts filter in a certain moment (just for a particular block of posts)

I want to apply a filter to a block of posts, for a custom field that I created, called: 'highlighted_in'. To

I want to apply a filter to a block of posts, for a custom field that I created, called: 'highlighted_in'. To filter the results I'm using the 'pre_get_posts' hook, and it works.

But I think my approach is very precarious. I had to do test and error with a var counter $_REQUEST["BQ_EXEC"] increase it until I get the value of the correct moment when performs the query that feeds the block of posts, in which I want to apply the filter.

This is the code, that I put in functions.php:

function my_post_filter($query) {

    if ( !is_admin() && !$query->is_main_query() ) {

        if ($query->is_home()  ) {
            // Query count var
            if ( !isset($_REQUEST["BQ_EXEC"]) )
                $_REQUEST["BQ_EXEC"] = 0;

            // The block i'm interested in is no. 5
            if ( $_REQUEST["BQ_EXEC"]==5 ) {
            // Set the custom field for this case
                $query->set( 'suppress_filters', false);
                $meta_query = $query->get('meta_query');
                if ( empty($meta_query) )
                    $meta_query = array();
                $meta_query[] = array(
                    'key'=>'highlighted_in',
                    'value'=>'home'
                );
                $query->set('meta_query', $meta_query);
            }
            $_REQUEST["BQ_EXEC"]++;
        }
    }
}

add_action('pre_get_posts','my_post_filter');

My question is: How can I link the call to the moment when the block is going to be executed? How can I put a hook when the block is going to consult the data? Because if the structure of the page changes, my solution would no longer be valid.

I have little experience in the world of Wordpress, so any other way of doing this you recommend is welcome. Thank you.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745317468a4622282.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信