【问题标题】:Wordpress how to filter posts basing on custom field in certain post typeWordpress如何根据某些帖子类型中的自定义字段过滤帖子
【发布时间】:2022-01-16 21:42:54
【问题描述】:

我有以下代码:

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

而且它工作得很好,但是它会在每个页面上自行执行。我希望它只在自定义帖子类型“customer_bill”单数中执行。

可以吗?

【问题讨论】:

    标签: php wordpress wordpress-theming custom-post-type custom-wordpress-pages


    【解决方案1】:

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

    • is_singleDocs 函数检查查询是否针对现有的单个帖子。

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

    【讨论】:

      【解决方案2】:

      试试:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-17
        • 2014-03-17
        • 1970-01-01
        • 2014-03-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-16
        相关资源
        最近更新 更多