首页 > 解决方案 > get the custom post type data using a custom field value in wordpress

问题描述

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?

Here is the code:

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

This code was not working.

标签: wordpresscustom-post-typeadvanced-custom-fields

解决方案


您的 AFC 字段是一个帖子对象,这意味着元值是单个帖子 ID,或者是帖子 ID 的序列化数组。

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

$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查询:

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

推荐阅读