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条)