Search code examples
phpwordpresswordpress-themingcustom-post-typecustom-wordpress-pages

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?


Solution

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