0

I'm trying to search for the latest post that has a custom taxonomy attached to it. I've used the Advanced Custom Fields plugin to add a custom taxonomy called 'brand_post_link' which allows users to tag a blog post with a brand, which is a taxonomy used with Woocommerce called 'product_brand'.

I have a product_brand taxonomy archive where I list all product brands and individual product brand pages which list all the products in that brand. What I then want to do is get the latest blog post which is tagged with that brand.

Here is the code I have to get all products for a brand used on the individual brand page:

$brandData = get_queried_object();
$args = array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'ignore_sticky_posts' => 1,
    'posts_per_page' => 12,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_brand',
            'field' => 'id',
            'terms' => $brandData->term_id
            )
        )
);
$brandProducts = new WP_Query($args);

This works fine, so here is the code I thought would work to get the most recent post for the specific brand:

$relatedBlogPostArgs = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 1,
    'order' => 'DESC',
    'orderby' => 'date',
    'tax_query' => array(
        array(
            'taxonomy' => 'brand_post_link',
            'field' => 'id',
            'terms' => $brandData->term_id
        )
    )
);
$relatedBlogPosts = new WP_Query($relatedBlogPostArgs);

This however doesn't return anything. Is there a fault in my logic or code somewhere or is the code correct and simply a case of matching up the correct name/id/taxonomy etc?

0

1 Answer 1

0

For the record I found an answer to this question in the end - I needed to use a meta query rather than a taxonomy query. The correct code ended up being this:

$relatedBlogPostArgs = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 1,
    'order' => 'DESC',
    'orderby' => 'date',
    'meta_query' => array(
        array(
            'key' => 'brand_post_link',
            'value' => $brandData->term_id
        )
    )
);
$relatedBlogPosts = new WP_Query($relatedBlogPostArgs);

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.