Thank you for your patience!
I was able to get it to work with the wp_get_post_categories()
function but I wrote this shortcode in my active theme’s functions.php file to be flexible with custom taxonomies as well, just in case.
function au_get_post_categories()
{
$post_id = 0;
global $post;
if (isset($post)) {
$post_id = $post->ID; // If the global
$post
object is set, get its ID
} else {
$post_id = get_the_ID(); // Otherwise get it from "the loop"
}
if ($post_id) {
$categories = wp_get_object_terms(
$post_id, // Get only the ones assigned to this post
'category', // Or a custom taxonomy
array('fields' => 'names') // Return an array of term names
);
if (is_array($categories) && count($categories)) {
// Return a string value for the text field input
return esc_attr(implode(', ', $categories));
}
return 'Categories not an array or is empty'; // Comment this out (or remove) when done testing
}
return 'Post ID could not be set'; // Return an empty string when done testing
}
add_shortcode('au_get_post_categories', 'au_get_post_categories', 10, 0);
And then in my contact form, I used this form tag:
[dynamictext post_categories "au_get_post_categories"]
As intended, it returned a comma delimited list of category names assigned to the current post the form was located on in this text field.
This was tested in my local WP environment on a native post
type using WordPress’s native category
taxonomy. Even if I unchecked all the categories while editing the post and then saved it, it defaulted to being assigned the “Uncategorized” category, so my two testing strings “Post ID could not be set” and “Categories not an array or is empty” never returned because the native WordPress behavior always ensures that every post has at least one category. Of course, themes, plugins, and other devs may override that so I have the checks just in case ?? Just be sure to remove the debugging language (noted in code comments) before using it in a production environment.
Cheers!