Site logo

Archived topic

Comments count in the page header

3 replies · Started by themedleb on October 24, 2017

Viewing posts 1–4 of 4

Hi there,

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 &ldquo;%s&rdquo;', '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 &ldquo;%2$s&rdquo;',
							'%1$s thoughts on &ldquo;%2$s&rdquo;',
							$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 &ldquo;%s&rdquo;', '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 &ldquo;%2$s&rdquo;',
							'%1$s thoughts on &ldquo;%2$s&rdquo;',
							$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?

Thank you in advance.

Yeah it is, thank you so much Tom.

You're very welcome! :)

This archived topic is closed to new replies.