I have a shortcode called [post_category] and [post_tag] that will show the category name and tag in the front end when posted in a normal post. However, I want to add this inside the Select Field in ACF. I tried adding [post_category] and [post_tag] in the field but when I tried to select it, the front-end still shows [post_category] and [post_tag] instead of the actual category name or tag name.
What I want is when I select any of them, I want it to show the category or tag name. How can you achieve that?
// Function to replace [post_category] and [post_tag] with the actual category and tag names.
function replace_shortcode_with_category_or_tag($value, $post_id, $field) {
if (is_string($value) && ($field['type'] === 'select' || $field['type'] === 'radio')) {
// Replace [post_category] with the actual category name.
$value = str_replace('[post_category]', get_the_category()[0]->name, $value);
// Replace [post_tag] with the actual tag name.
$value = str_replace('[post_tag]', get_the_tags()[0]->name, $value);
}
return $value;
}
// Hook into 'acf/load_value' filter to replace the shortcode with category/tag names.
add_filter('acf/load_value', 'replace_shortcode_with_category_or_tag', 10, 3);
I assumes you have a single category and tag assigned to each post. If a post has multiple categories or tags, you might need to adjust the code accordingly to handle multiple categories/tags. Also, make sure to use the correct field names and handle any error scenarios to ensure smooth functionality.