You can use the title
parameter in the shortcode to add a title above the listing of posts. But what if you want that title to dynamically include the post count?
We’ll use the shortcode_atts_display-posts
filter to modify the default parameters for the shortcode. If the shortcode does not have a title specified, we’ll give it a placeholder title of [dps_dynamic_post_count]
. This way we don’t override titles you have manually specified.
After the query has run and right before the shortcode is rendered, we’ll use the do_shortcode_tag
filter to change this placeholder to the actual text.
We’ll use the global $dps_listing
variable, which stores the WP_Query used by Display Posts:
$dps_listing->post_count
returns the number of posts in the current listing, which is what we’ll be using.$dps_listing->found_posts
returns the total number of posts matching the current query, which could be more than are displayed currently. You may want to use this if you’re also using the Pagination extension.
Finally, we’ll use the _n()
function to include “Post” in the title if there’s only one, or “Posts” if there’s more than one.
/**
* Display Posts - Post Count Title Placeholder
* [dps_dynamic_post_count] will be filtered later after the query has run
*
* @see https://displayposts.com/2019/08/14/display-post-count-as-title-of-listing/
*
* @param array $out, the output array of shortcode attributes (after user-defined and defaults have been combined)
* @param array $pairs, the supported attributes and their defaults
* @param array $atts, the user defined shortcode attributes
* @return array $out, modified output of shortcode attributes
*/
function be_dps_post_count_title_placeholder( $out, $pairs, $atts ) {
if( empty( $atts['title'] ) )
$out['title'] = '[dps_dynamic_post_count]';
return $out;
}
add_filter( 'shortcode_atts_display-posts', 'be_dps_post_count_title_placeholder', 10, 3 );
/**
* Display Posts - Post Count Title
* Replace [dps_dynamic_post_count] with actual post count from $dps_listing
*
* @see https://displayposts.com/2019/08/14/display-post-count-as-title-of-listing/
*
* @param string $output, the shortcode output
* @param string $tag, the shortcode tag
* @return string $output, the modified shortcode output
*/
function be_dps_post_count_title( $output, $tag ) {
if( 'display-posts' !== $tag )
return $output;
global $dps_listing;
if( !empty( $dps_listing->post_count ) ) {
$title = sprintf( _n( '%d Post', '%d Posts', $dps_listing->post_count ), $dps_listing->post_count );
} else {
$title = '';
}
$output = str_replace( '[dps_dynamic_post_count]', $title, $output );
return $output;
}
add_filter( 'do_shortcode_tag', 'be_dps_post_count_title', 10, 2 );
Filters used:
do_shortcode_tag
shortcode_atts_display-posts