Display Posts lists 10 posts by default, but you can change this using the posts_per_page
parameter in a shortcode.
For instance, if you only wanted to list two posts, use:
[display-posts posts_per_page="2"]
If you want to list every post, use “-1” as the value:
[display-posts posts_per_page="-1"]
Set new default for posts_per_page
If you find yourself typing the same value for posts_per_page in most of your shortcodes, it might be a good idea to set that as the default on your website.
The following code changes the default to 20 (change this to whatever you’d like it to be).
/**
* Set Defaults in Display Posts Shortcode
* @see https://displayposts.com/2019/01/04/change-default-attributes/
*
* @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
*/
function be_dps_defaults( $out, $pairs, $atts ) {
$new_defaults = array(
'posts_per_page' => 20,
);
foreach( $new_defaults as $name => $default ) {
if( array_key_exists( $name, $atts ) )
$out[$name] = $atts[$name];
else
$out[$name] = $default;
}
return $out;
}
add_filter( 'shortcode_atts_display-posts', 'be_dps_defaults', 10, 3 );
Now if you use [display-posts]
without a posts_per_page
parameter, it will list 20 posts.
You can still change this on a per-shortcode basis by using the posts_per_page
parameter. The following shortcode will display 2 posts:
[display-posts posts_per_page="2"]
Use value in Settings > Reading as default
WordPress lets you how many posts to display on archive pages in Settings > Reading. The following code will use that value as the default for Display Posts as well.
/**
* Set Defaults in Display Posts Shortcode
* @see https://displayposts.com/2019/01/04/change-default-attributes/
*
* @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
*/
function be_dps_defaults( $out, $pairs, $atts ) {
$new_defaults = array(
'posts_per_page' => intval( get_option( 'page_for_posts' ) ),
);
foreach( $new_defaults as $name => $default ) {
if( array_key_exists( $name, $atts ) )
$out[$name] = $atts[$name];
else
$out[$name] = $default;
}
return $out;
}
add_filter( 'shortcode_atts_display-posts', 'be_dps_defaults', 10, 3 );