Wordpress 如何根据某些 post 类型的自定义字段过滤 posts

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

我有以下代码:

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

它运行良好,但它会在每个页面上自行执行。我希望它只在自定义 post 类型“customer_bill”单数中执行。

可以吗?

您可以使用以下条件来更改查询:

  • is_singleDocs 函数检查查询是否针对现有的单个 post.

  • 对“$query”变量使用 get('post_type') 方法。
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);
    }
}

尝试:

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

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