I'm trying to create a shortcode to display the post categories with custom format (ex.: I need to display emoji acf field before each category).
I'm using version 6.0 of WordPress and the Full Site Editing to create the templates. I've added the shortcode in the single post template and inside the query loop block in the index template. It works fine for each single post page, but in the index page with all posts listed is showing the same category (the category of the first post) for every post.
I'm new to php and WordPress development. Any help on how to solve this issue will be much appreciated.
Code for the shortcode below:
function my_theme_post_categories_shortcode() {
$post_id = get_the_ID();
$post_categories = get_the_category( $post_id );
$output = '';
if ( $post_categories ) {
foreach( $post_categories as $category ) {
$category_emoji = get_term_meta( $category->term_id, 'emoji', true);
$category_color = get_term_meta( $category->term_id, 'category_color', true);
$output .= '<a href="' . esc_url(get_category_link( $category->term_id )) . '" style="color: var(--wp--preset--color--' . $category_color . ');">' . '<span class="emoji" aria-hidden="true">' . $category_emoji . '</span>' . $category->cat_name . '</a>';
}
}
return '<div class="post-categories">' . $output . '</div>';
}
add_shortcode( 'post_categories', 'my_theme_post_categories_shortcode' );
I've managed to add the emoji to the core categories list block that lists all categories via filters, with the following code. But I can't manage to do the same for the core post terms categories that lists the categories of each post.
function my_theme_custom_list_categories( $list ) {
$categories = get_categories();
if ( $categories ) {
foreach( $categories as $cat ) {
$cat_emoji = get_term_meta( $cat->term_id, 'emoji', true);
$find = '<a href="' . esc_url(get_term_link( $cat )) . '">';
$replace = '<a href="' . esc_url(get_term_link( $cat )) . '">' . '<span class="emoji" aria-hidden="true">' . $cat_emoji . '</span><span class="cat-name">';
$list = str_replace( $find, $replace, $list );
$find = '</a>';
$replace = '</span></a>';
$list = str_replace( $find, $replace, $list );
}
}
return $list;
}
add_filter( 'wp_list_categories', 'my_theme_custom_list_categories');
get_the_ID
and hoping for the best