Wordpress how to filter posts basing on custom field in certain post type
You could use the following conditions to alter the query:
-
is_single
Docs function to check whether the query is for an existing single post.
AND
- Using
get('post_type')
method on the "$query" variable.
add_action('pre_get_posts', 'filter_by_user', 9998);
function filter_by_user($query)
{
if (
is_single()
&&
'customer_bill' == $query->get('post_type')
)
{
$user = get_current_user_id();
$meta_query = $meta_query ?: [];
$meta_query[] = [
'key' => 'id_customerJK',
'value' => $user,
'compare' => 'LIKE',
];
$query->set('meta_query', $meta_query);
}
}
Try :
if ( is_singular('customer_bill') ) {
// Your Code
or
if ( ! is_singular('customer_bill') ) {
return;
}
// Your Code