wp query – Querying Custom Post Type with Custom Taxonomy using an ACF Field Value as a Variable


we use an ACF text field to manually add a text string which is then used to pull in related posts which have the same core tag, i.e., when the ACF meta field value is ‘example-string’, all posts tagged with ‘example-string’ will be shown on the page.

We also have a custom post type called ‘Articles’ and a custom taxonomy called ‘Article Tags’ and we’re trying to check for the presence of an ‘article_tag’ using the same ACF field that we use to check core tags. We need to do this because the shortcode we use them with requires us return them as a comma separated list of ‘IDs’ in order for it to work.

We’ve tried to use wp_list_pluck but it’s the tax_query part of the $args that seems to be causing the issue because it uses a variable to include the ACF meta field value.

Here’s what I’ve got which currently returns nothing. It should return a comma separated list of post ID(s) for any articles which have the article_tag that matches the get_field(‘mk_acf_sh_rel_tag’).

$mk_acf_sh_tag = get_field('mk_acf_sh_rel_tag');
    $mk_sh_articles_args = array(
        'post_type' => 'article',
        'tax_query' => 
                'taxonomy' => 'article_tag', 
                'field'    => 'slug',              
                'terms'    => $mk_acf_sh_tag

    $mk_sh_articles_query = new WP_Query($mk_sh_articles_args);

    $mk_sh_articles_query_ids = wp_list_pluck($mk_sh_articles_query->posts,'ID');
    $mk_sh_articles_query_ids_string = implode(',', $mk_sh_articles_query_ids);
    echo do_shortcode('[post_block_shortcode post_ids="'.$mk_sh_articles_query_ids_string.'"]');


MattK1984 1 year 2022-10-09T17:03:36-05:00 0 Answers 0 views 0

Leave an answer