Home › Forums › General Issues › Get ACF Category Image into Shortcode Loop
Hello ACF members, hope you’re all having a wonderful day!
For the last couple of hours i’ve been trying to add a category image (created from ACF) to a shortcode i use to call sub-categories from the current category. This has proven to be to much challenging for me because my PHP skills are basically 0. I usually try to find the most similar code i can get and do basic changes for my needs.
Here’s the current shortcode function i’m using to display sub categories of the current category page:
add_shortcode( 'list_subcategories', function() {
ob_start();
$current_cat = get_queried_object();
$term_id = $current_cat->term_id;
$taxonomy_name = 'category';
$term_children = get_term_children( $term_id, $taxonomy_name );
echo '<ul class="cat-parents">';
foreach ( $term_children as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '" class="testing">' . $term->name . '</a></li>';
}
echo '</ul>';
return ob_get_clean();
} );
The ACF field i want to display inside the loop is: category_image
This is where i’m at but it doesn’t work:
add_shortcode( 'list_subcategories', function() {
ob_start();
$current_cat = get_queried_object();
$term_id = $current_cat->term_id;
$taxonomy_name = 'category';
$image = get_field('category_image', $current_cat );
$term_children = get_term_children( $term_id, $taxonomy_name, $image );
echo '<ul class="cat-parents">';
foreach ( $term_children as $child ) {
$term = get_term_by( 'id', $child, $taxonomy_name );
echo '<li><div class="test">'. $image .'</div><a href="' . get_term_link( $child, $taxonomy_name ) . '" class="testing">' . $term->name . '</a></li>';
}
echo '</ul>';
return ob_get_clean();
} );
What am i doing wrong? Can someone give me a hand? This is probably something very simple that i’m missing.
the image of the sub category or the image of the parent category
this is correct for the parent term
$image = get_field('category_image', $current_cat );
this would be used for the child term
$image = get_field('category_image', $child );
however, this may not be returning what you expect it to return, and what it is returning would depend on where you are adding the shortcode.
$current_cat = get_queried_object();
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.