[英]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.
我希望它只在自定义帖子类型“customer_bill”单数中执行。
Is it possible to do so?有可能这样做吗?
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. is_single
Docs function 检查查询是否针对现有的单个帖子。 AND和
get('post_type')
method on the "$query" variable.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);
}
}
Try:尝试:
if ( is_singular('customer_bill') ) {
// Your Code
or或者
if ( ! is_singular('customer_bill') ) {
return;
}
// Your Code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.