我可以在 Wordpress 编辑器中将 3 个最近发布的列表动态输出到默认文本中吗?
Can I dynamically output a list of 3 recent posts into default text in Wordpress editor?
我希望有人能帮助我学习如何实现这一目标。
我的想法是从一个类别(热门帖子)中生成一个包含 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;
}
请问有什么办法可以实现吗?
在 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;
}
我希望有人能帮助我学习如何实现这一目标。
我的想法是从一个类别(热门帖子)中生成一个包含 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;
}
请问有什么办法可以实现吗?
在 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;
}