wordpress - 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.
解决方案
您的 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)
);`
推荐阅读
- java - 如何使用 dom4j 添加默认名称空间?
- excel - 将数据透视表从一个数据模型导入到另一个数据模型
- computer-vision - .SMOTE 库问题
- visual-studio - 我不能在编辑器区域打开更多 3 个文件
- sql - SQL Inner join 如何只显示一次组合
- python - 创建数据透视表时出现关键错误
- php - 使用选项数组在 php 7.4 版中未设置 Cookie?
- c++ - for (int i = 2; i < n; i = i*i) 的时间复杂度是多少?
- python - 如何单击 recaptchaV2 的使用 Selenium 和 Python 解决挑战按钮
- python - 尽管没有错误和警告,但 Kivy 应用程序中出现黑屏