• Resolved issues.inc

    (@issuesinc)


    Hello!

    I need to display the last 5 posts of a chosen category on a page template.
    Looking into the documentation, I can use an association field to display a list of all the site’s categories on the page edit screen so the posters can choose one. How can I display the chosen category ID on my template so I can insert it into a post loop?

    I’ve used “carbon_get_post_meta(get_the_ID(), ‘my_association_field’);” but it only displays the word “Array” on the template, no IDs or category names.

    Thanks

Viewing 1 replies (of 1 total)
  • Magi1053

    (@magi1053)

    Associations and Relationships return an array of Post/Term IDs. If you are only selecting one item in the association, you can simply do carbon_get_post_meta(get_the_ID(), 'my_association_field')[0] to get the first (only) element in the array, otherwise if you would like to display all of the categories, you could put them inside of a foreach loop, for example:

    foreach ( carbon_get_post_meta( get_the_ID(), 'my_association_field' ) as $category ) :
        $query = new WP_Query( array( 'cat' => $category->ID ) );
        if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
            // All posts with this category
        endwhile; endif;
    endforeach;

    Please note that this code is untested
    If you just wanted to get the category itself, you could use the function get_the_category_by_ID( int $cat_ID )

    • This reply was modified 8 years ago by Magi1053.
    • This reply was modified 8 years ago by Magi1053.
    • This reply was modified 8 years ago by Magi1053.
Viewing 1 replies (of 1 total)
  • The topic ‘Association Field Question’ is closed to new replies.