I have the following bit of code:

$args = array(
    'posts_per_page'   => -1,
    'category'         => 7,
    'orderby'          => 'name',
    'order'            => 'ASC',
    'post_type'        => 'product'
);

$posts = get_posts($args);var_dump($posts);

This should return one post I know that is in the category, but it isn’t. If I leave out the ‘category’-argument, I get all the products, so I know this should normally work. If I change the category to 1 and take out my custom post type (product), I get my default posts.

I can’t see what’s wrong with this. Can anyone spot what the problem is?

2 s
2

In all probability you are using a custom taxonomy, and not the build-in category taxonomy. If this is the case, then the category parameters won’t work. You will need a tax_query to query posts from a specific term. (Remember, get_posts uses WP_Query, so you can pass any parameter from WP_Query to get_posts)

$args = [
    'post_type' => 'product',
    'tax_query' => [
        [
            'taxonomy' => 'my_custom_taxonomy',
            'terms' => 7,
            'include_children' => false // Remove if you need posts from term 7 child terms
        ],
    ],
    // Rest of your arguments
];

ADDITIONAL RESOURCES

  • What is the difference between custom taxonomies and categories
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *