I want to filter posts in such a way that only posts, for which get_post_meta($post->ID, "project_cat", true) (it returns a post ID) is equal to my specified value, are shown.
Any way to do this?
I am especially interested in ways to do it compatible with WP-Paginate plugin.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The WP_Query object accepts a post meta argument. Generally speaking you want to do the following:
$my_query = new WP_Query(
array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'project_cat',
'value' => 'my-value',
)
),
// Other query properties
)
);
Where ‘my-value’ is your ‘specified value’.
Example usage:
add_action( 'pre_get_posts' , 'my_pre_get_posts' );
function my_pre_get_posts( $query ) {
// Check this is main query and other conditionals as needed
if( $query->is_main_query() ) {
$query->set(
'meta_query',
array(
array(
'key' => 'project_cat',
'value' => 'my-value'
)
)
);
}
}
See WP_Query, pre_get_posts. All conditionals are available to you. Currently this runs on every main query – which you probably don’t want.
Alternatively you can use query_posts (a simpler, but much less efficient way) to alter the query for only a specific instance in a template.
Method 2
you can filter the post based on the meta value and display the post on the cms page.
'meta_query' => array(
array(
'key' => 'front_page',
'value' => 'yes',
'compare' => 'LIKE',
))
please refer the tutorial for step by step explanation
http://www.pearlbells.co.uk/filter-posts-custom-fields-wp_query/
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0