我可以在Wordpress编辑器中将3个最新帖子的列表动态输出为默认文本吗?

时间:2019-12-24 10:27:25

标签: php wordpress wordpress-hook

我希望有人可以帮助我学习如何实现这一目标。

我的想法是从一个类别(排名靠前的帖子)生成3个最新帖子的列表,作为wordpress编辑器中的默认文本。

我研究了几种解决方案,以实现相似的目的,并将其混合到下面的代码中,但似乎不起作用。

add_filter('default_content', 'tp4567_default_list');
function tp4567_default_list( $content ) {
$content = new WP_Query( 'cat=2&posts_per_page=3' );
return $content;
} 

请问有什么办法可以实现这一目标?

1 个答案:

答案 0 :(得分:0)

在functions.php中尝试此代码,它将起作用。

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;
}