问题
I was hoping someone could help me learn how to achieve this.
My idea is to generate a list of 3 recent posts from a category (top posts) as a default text in the wordpress editor.
I looked at several solutions to achieve something similar and kind of mixed them into the code below, but it doesn't seem to work.
add_filter('default_content', 'tp4567_default_list');
function tp4567_default_list( $content ) {
$content = new WP_Query( 'cat=2&posts_per_page=3' );
return $content;
}
Is there any way I can achieve this, please?
回答1:
Try this code in functions.php, it will work.
add_filter( 'default_content', 'wp_my_default_content', 10, 2 );
function wp_my_default_content( $content, $post )
{
// get the posts
$posts = get_posts(
array(
'numberposts' => 3
)
);
// No posts? run away!
if( empty( $posts ) ) return '';
$content = '<ul>';
foreach( $posts as $post )
{
$content .= sprintf(
'<li><a href="%s" title="%s">%s</a></li>',
get_permalink( $post ),
esc_attr( $post->post_title ),
esc_html( $post->post_title )
);
}
$content .= '</ul>';
return $content;
}
来源:https://stackoverflow.com/questions/59467366/can-i-dynamically-output-a-list-of-3-recent-posts-into-default-text-in-wordpress