0

I am facing a little problem whilst trying to display posts, from certain categories, on the front end. I've created a custom field whose key is 'related_categories' and I've different categories with slugs such as 'army', 'navy', 'airforce' etc.

When creating a new custom post, I enter the slugs of different categories inside the 'related_categories' custom field, for e.g. 'navy', 'airforce', and this is the code which I've inside my template file to echo the custom field values inside the 'tax_query' array.

<?php global $post;

$related = array ( get_post_meta($post->ID, 'related_categories', true) );

$the_query = new WP_Query( array( 'post_type' => 'medals', 'posts_per_page' => 3, 'tax_query' => array( array( 'taxonomy' => 'medal-categories', 'field' => 'slug', 'terms' => $related, ), ), ) ); 

while ( $the_query->have_posts() ) : $the_query->the_post(); 

//loop starts after this

Now the problem which I am facing is that if I enter only one slug inside the 'related_categories' custom field, for e.g. 'navy', then the posts from the 'navy' category successfully show up but if I enter more than one slug inside the 'related_categories' custom field, for e.g. 'navy', 'army', then the posts do not show up.

I tried searching for a solution on the internet but couldn't find any therefore any help would be appreciated. Thank you.

1 Answer 1

0

The problem is that you are passing a comma separated list of terms, not an array of term. For example, if you enter 'army,navy,airforce' in the custom field:

$related = array ( get_post_meta($post->ID, 'related_categories', true) );
//$related = array('army,navy,airforce');
//What you need is
//$related = array('army','navy,'airforce');

You need to transform each term into a array member, for example using explode:

$related = explode(',', trim( get_post_meta($post->ID, 'related_categories', true) ) );

Anyway, I think that you should think in another way to get your purpose. Using a custom field to manual store a list a related categories is not appropiate from my point of view. You could created, for example, a hierarchical taxonomy and set related categories under the same parent, or use the core tag taxonomy to set relationships, etc, I think this is better and more "natural" than using a custom field to store a set of taxonomy terms.

3
  • Would it be possible for you to show me how the functionality, which I require, can be achieved using the explode function? Commented Aug 21, 2014 at 6:36
  • See edited answer. explode() is just a native PHP function. For reference see the link to explode documentation in PHP site.
    – cybmeta
    Commented Aug 21, 2014 at 14:25
  • that worked like a charm! thanks a lot for your help. Commented Aug 21, 2014 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.