I am building a block theme for WordPress.
I wrote a shortcode function that is supposed to output the message "By [author’s display name with author’s link]".
More specifically, I am trying to use it in the search result loop (main loop for the search result template).
function auteur_par(){
$auteur = get_the_author();
$auteur_nom = get_the_author_meta('display_name', $auteur);
$auteur_url = get_the_author_meta('user_url', $auteur);
return '<p>Par <a href="' . $auteur_url . '" target="_self" class="wp-block-post-author-name__link">' . $auteur_nom . '</a></p>';
}
add_shortcode('auteur_par', 'auteur_par');
I also tried using get_the_author_meta
directly:
function auteur_par(){
$auteur_nom = get_the_author_meta('display_name');
$auteur_url = get_the_author_meta('user_url');
return '<p>Par <a href="' . $auteur_url . '" target="_self" class="wp-block-post-author-name__link">' . $auteur_nom . '</a></p>';
}
add_shortcode('auteur_par', 'auteur_par');
Both don’t work work when I use it as a shortcode within the "Modèle de publication" block (I can’t find what the english name is for this block, it’s the block under the query loop block in the outline). On the page, the paragraph is there, but the variables are empty.
I made a similar function using get_the_modified_date()
and that one works perfectly. I don’t understand why it works for the modification date but not for the author.
I tried the solutions referenced in this post and this post but it doesn’t work.
2
Answers
You need to get the Author ID like in your 2nd linked thread, then from that author ID you will be able to get the WP_User related object and get any user data from the author.
Try the following:
It should work now.
Usage:
[auteur_par]
You can use the below shortcode to retrieve and display the author data within the WordPress loop. Add the following code to your theme’s functions.php file: