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)
);`
I think this may help you. Please have a look at this.
Can I get the data using custom field value? -- Yes, you can get the data using custom field value.
First, we can get the custom field value by using the below code.
<?php $custom_field_value= get_post_meta( get_the_ID(), 'generic-name', true ); ?>
This $custom_field_value return the value of 'generic-name' field.
By using that value we can form WP_Query.
$the_query = new WP_Query( array(
'posts_per_page'=>9,
'post_type'=>'brand-name',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'generic-name',
'value' => $custom_field_value
),
),
'paged' => get_query_var('paged') ? get_query_var('paged') : 1)
);
Thanks.