Tim
Tim

Reputation: 87

Wordpress how to filter posts basing on custom field in certain post type

I have the following code:

function filter_by_user( $query ) {
      
$user = get_current_user_id();

if ( ! $meta_query ) {
    $meta_query = [];
}

// Append our meta query
$meta_query[] = [
    'key'     => 'id_customerJK',
        'value'   => $user,
        'compare' => 'LIKE',
];

$query->set( 'meta_query', $meta_query );
}
    add_action( 'pre_get_posts', 'filter_by_user', 9998 );

And it works very well, however it executes itself on every page. I would like it to only execute in the custom post type "customer_bill" singular.

Is it possible to do so?

Upvotes: 1

Views: 851

Answers (2)

Sam
Sam

Reputation: 591

Try :

if ( is_singular('customer_bill') ) {
// Your Code

or

if ( ! is_singular('customer_bill') ) {
    return;
}
// Your Code

Upvotes: 1

Ruvee
Ruvee

Reputation: 9097

You could use the following conditions to alter the query:

  • is_singleDocs 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);
    }
}

Upvotes: 3

Related Questions