1

I am trying to retrieve all the post associated with my custom taxonomy term. My custom taxonomy is "Stores". I am using the following code.

$posts = get_posts(array(
                  'post_type' => 'coupon',
                  'numberposts' => -1,
                  'post_status' => array('publish', 'unreliable', 'draft'),
                  'tax_query' => array(
                    array(
                      'taxonomy' => 'stores',
                      'field' => 'name',
                      'terms' => 'New Store', 
                      'include_children' => false
                    )
                  )
                ));

My taxonomy term name is "New Store". Just because it has a space in the title I couldn't get any posts associated with it. I tried the same code on a taxonomy term without a space in the title and it worked.

Any help will be appreciated. Thanks.

1

You could get the posts by slug instead of name. Like this:

$posts = get_posts(array(
    'post_type' => 'coupon',
    'numberposts' => -1,
    'post_status' => array('publish', 'unreliable', 'draft'),
    'tax_query' => array(
        array(
            'taxonomy' => 'stores',
            'field'    => 'slug',
            'terms'    => array( 'new-store' ),
            'include_children' => false
        )
    )
));

Or you could get the posts by term id. like this:

$posts = get_posts(array(
    'post_type' => 'coupon',
    'numberposts' => -1,
    'post_status' => array('publish', 'unreliable', 'draft'),
    'tax_query' => array(
        array(
            'taxonomy' => 'stores',
            'field' => 'term_id',
            'terms' => array( 4 ),
            'include_children' => false
        )
    )
));

Here you can find a guide on how to know the term id: https://facetwp.com/how-to-find-a-wordpress-terms-id/

| improve this answer | |
  • Thanks for your help but i am specifically looking to get the posts via term name. – Sid Apr 3 '17 at 10:47
1

Nevermind, i just extracted the taxonomy term id from name and then extarcted the custom posts from it. Here is the code if anyone is looking:

$term = get_term_by('name', 'New Store', 'stores');

            $posts = get_posts(array(
              'post_type' => 'coupon',
              'numberposts' => -1,
              'post_status' => array('publish', 'unreliable'),
              'tax_query' => array(
                array(
                  'taxonomy' => 'stores',
                  'field' => 'id',
                  'terms' => $term->term_id, 
                  'include_children' => false
                )
              )
            ));
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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