使用wordpress中的自定义字段值获取自定义帖子类型数据 [英] get the custom post type data using a custom field value in wordpress

查看:413
本文介绍了使用wordpress中的自定义字段值获取自定义帖子类型数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用自定义字段值获取数据吗?我的 post_type 品牌名称,字段名称是通用名称。那么如何使用通用名称获取所有数据?

Can I get the data using custom field value? My post_type is brand-name and the field name is generic-name. So How can I get all the data using the generic-name?

这是代码:

$title = get_the_title(); 
$the_query = new WP_Query( array(
          'posts_per_page'=>9,
          'post_type'=>'brand-name',
          'order'   => 'ASC',
          'meta_query' => array(
           array(
                'key' => 'generic-name',// this key is advance custom field: type post_object
                'value' => $title,
                'type'  => 'char' // type not working
           ), 
        ), 
        'paged' => get_query_var('paged') ? get_query_var('paged') : 1) 
      );`

此代码无法正常工作。

推荐答案

您的AFC字段是post对象,这意味着meta值是

Your AFC field is a post object, which means the meta value is either a single post id, or a serialized array of post ids.

如果您的自定义字段设置为仅允许单个选择,则它将是单个ID,并且可以这样查询:

If your custom field is set to only allow a single selection, then it will be a single id, and can be queried like this:

$post_id = get_the_ID(); 
$the_query = new WP_Query( array(
      'posts_per_page'=>9,
      'post_type'=>'brand-name',
      'order'   => 'ASC',
      'meta_query' => array(
       array(
            'key' => 'generic-name',// this key is advance custom field: type post_object
            'value' => $post_id,
       ), 
    ), 
    'paged' => get_query_var('paged') ? get_query_var('paged') : 1) 
  );`

如果您的自定义字段允许多项选择,那么它将序列化php ID数组。由于mysql不知道如何读取php序列化数据,因此您最好的方法是使用 Like 查询:

If your custom field allows multiple selection, then it will a serialized php array of ids. Since mysql does not know how to read php serialized data, the best you can do is use a LIKE query:

$post_id = get_the_ID(); 
$the_query = new WP_Query( array(
      'posts_per_page'=>9,
      'post_type'=>'brand-name',
      'order'   => 'ASC',
      'meta_query' => array(
       array(
            'key' => 'generic-name',// this key is advance custom field: type post_object
            'value' => sprintf("\"%s\"", $post_id),
            'compare' => 'LIKE'
       ), 
    ), 
    'paged' => get_query_var('paged') ? get_query_var('paged') : 1) 
  );`

这篇关于使用wordpress中的自定义字段值获取自定义帖子类型数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆