The code you want to insert needs to be modified for use in a shortcode callback because shortcode callbacks must not ever echo out content. Instead, all output should be collected into a single variable. Before starting a foreach loop, initialize a variable by assigning an empty string or the first part of the output. For example:
$output = '';
or $output = '<strong>';
Anywhere content is output, such as with echo
, instead concatenate the output to $output. For example:
$output .= $category->cat_name . ' ';
But if the category name needs to maybe be translated it will be more complicated than this. Addressed below. Also, are you sure about cat_name
? That’s an unusual object property if we’re using WP_Term objects. I think you want $category->name
.
After the foreach loop completes, don’t forget the closing strong tag:
$output .= '</strong>';
Where all of this goes into your current shortcode callback depends on where you want output to occur in relation to post meta content. Before or after? Then add the category code before or after the post meta code.
Modify the post meta code. Instead of returning content, concatenate post meta content to $content. In the end after all is said and done, you will finally do:
return $content;
Now, how to work in possible translations of category names. The first thing your function should do is get the locale’s 2 character language code so you can use it to get the right translation. Let’s say the language code is assigned to $lang
. Then you could get the right language’s post meta with something like:
$output .= get_post_meta( $post->ID, 'incipit_'.$lang, true );
You’d do something similar for category names, except there is only term meta for non-Italian languages. If the locale language is “it”, $category->name is fine, but otherwise it has to come from term meta. Thus you need to determine the right value to output before concatenating it to $output. Instead of just
$output .= $category->name . ' ';
do something like:
$output .= 'it' == $lang ? $category->name : get_term_meta( category->term_id, 'tipologia_'.$lang, true) .' ';
In case you’re not familiar with the $condition ? 'its true':'its false';
construct, it’s a kind of shorthand for typical if/then/else statements. It’s called a “ternary” statement. It’s equivalent to:
if ( $condition ) {
'its true';
} else {
'its false';
}
Will this become the code I was asking for in your other topic about filtering a taxonomy for German? Then I guess I’m answering my own question 🙂 No filtering is necessary with this approach.
Do note that this requires you to alter the meta key names to be similar to tipologia_de, tipologia_en, tipologia_fr, etc. This means updating the code that saves term custom field data related to translated term names.