I have the following code and its not working because the array is not responding as expected. I am creating category selection on WordPress metabox and stored in the database as serialized data but when using tax_query
to fetch the selected categories, the array fails for separated the category id in the terms
field. Check the code below:
$selected_categories = get_post_meta($post->ID, $prefix . 'services_category', true);
if ($selected_categories != '') {
$categories = unserialize(get_post_custom($post->ID)[$prefix . 'services_category'][0]);
}
$cat_query = '';
$cat_query = ( !empty($categories) ) ? implode(',', $categories) : '';
if ($cat_query != '') {
$tax_query = array(
array(
'taxonomy' => 'services_cat',
'field' => 'id',
'terms' => array($cat_query),
),
);
} else { $tax_query = null; }
$services_paged = is_front_page() ? get_query_var( 'page' ) : get_query_var( 'paged' );
query_posts(array(
'post_type' => 'mt-services',
'posts_per_page' => $services,
'paged' => $services_paged,
'tax_query' => $tax_query
));
Here is where my question lies: I'm trying to echo the selected categories from metabox but unfortunately they are all echoed as one item.
'terms' => array($cat_query)
Here's the result:
print_r(array($cat_query)
gives me
Array ( [0] => 73,72 )
instead of
Array ( [0] => 73, [1] => 72 )
Detailed explanation
$categories
values are 73 and 72.
Using implode function we get $cat_query which
is (73,72)
.
Hence the array($cat_query)
would be array(73,72)
which when printed out should be:
Array ( [0] => 73, [1] => 72 )
But instead, $cat_query values are taken as a unit which ends up being printed out as:
Array ( [0] => 73,72 )
which is wrong
$cat_query
is created from $categories
with the function implode. So I assume that $categories
is an array that looks like the one you want:
Array ( [0] => 73, [1] => 72 )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.