Support

Account

Home Forums General Issues Taxonomy field in array

Solved

Taxonomy field in array

  • Hi,

    i’m trying to show all post from selected categories with Taxonomy field
    i’m using this code

    $kat = get_field('taxonomy');
     $args = array(
        'posts_per_page' => 5,
        'category__and' => array($kat)
    );
    $my_query = new WP_Query( $args );
    while( $my_query->have_posts() ):
        $my_query->the_post();
        the_title();
    endwhile;
    wp_reset_postdata(); 

    but I don’t get any results. When i echo $kat i’m getting ‘Array’
    Sorry if it’s a basic question but how to get this working as i don’t want to use text field with manualy given category id’s.

    thanks
    DR

  • Hi @sagi

    First, please make sure that you’ve set the “Return Value” to “Term ID”. This setup will make it returns an array of IDs from the selected taxonomies. That way, you don’t need to wrap the returned value in an array.

    Second, “category__and” args is used to show posts that have all of the selected taxonomies. If you want to show posts that have minimum one of the selected taxonomies, please use “category__in” instead. This page should give you more idea about it: https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters.

    So it should be something like this:

    $kat = get_field('taxonomy');
    $args = array(
        'posts_per_page' => 5,
        'category__in' => $kat, //change to category__and if you want to match all selected taxonomies
    );
    $my_query = new WP_Query( $args );
    while( $my_query->have_posts() ):
        $my_query->the_post();
        the_title();
    endwhile;
    wp_reset_postdata();

    If you want to check the returned value, please use the var_dump() function. This page should give you more idea about it: http://www.advancedcustomfields.com/resources/debug/.

    I hope this helps.

  • Thanks James,
    i knew i would be a basic question… category__and is what it should be.
    btw. i can’t live without ACF 😉

    thanks again
    DR

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Taxonomy field in array’ is closed to new replies.