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.
解决方案
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.
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)
);`
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)
);`