Can I dynamically output a list of 3 recent posts into default text in Wordpress editor?

纵饮孤独 提交于 2020-02-07 01:59:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!