I’m trying to insert comment count in a Page Header using a shortcode, I got the comments-count code from your “comments.php” file:
<h3 class="comments-title">
<?php
$comments_number = get_comments_number();
if ( 1 === $comments_number ) {
printf(
/* translators: %s: post title */
esc_html_x( 'One thought on “%s”', 'comments title', 'generatepress' ),
'<span>' . get_the_title() . '</span>'
);
} else {
printf( // WPCS: XSS OK.
/* translators: 1: number of comments, 2: post title */
esc_html( _nx(
'%1$s thought on “%2$s”',
'%1$s thoughts on “%2$s”',
$comments_number,
'comments title',
'generatepress'
) ),
number_format_i18n( $comments_number ),
'<span>' . get_the_title() . '</span>'
);
}
?>
</h3>
And tried to put it into a shortcode function like this:
function custom_shortcode() {
<h3 class="comments-title">
<?php
$comments_number = get_comments_number();
if ( 1 === $comments_number ) {
printf(
/* translators: %s: post title */
esc_html_x( 'One thought on “%s”', 'comments title', 'generatepress' ),
'<span>' . get_the_title() . '</span>'
);
} else {
printf( // WPCS: XSS OK.
/* translators: 1: number of comments, 2: post title */
esc_html( _nx(
'%1$s thought on “%2$s”',
'%1$s thoughts on “%2$s”',
$comments_number,
'comments title',
'generatepress'
) ),
number_format_i18n( $comments_number ),
'<span>' . get_the_title() . '</span>'
);
}
?>
</h3>
}
add_shortcode( 'commentscount', 'custom_shortcode' );
But when putting this code in Snippets plugin it always give me an error, which means I need to remove the html tags:
The code snippet you are trying to save produced a fatal error on line 2:
syntax error, unexpected ‘<‘
In the other hand, when I put the code (without shortcode function) into for example the single-post.php file it works fine, and when I put the code in Snippets with the shortcode function and without html tags (<h3 class=”comments-title”>) it works, is there anything I miss here?