问题描述
我创建了一个名为 Professionals 的自定义帖子类型。我正在使用 Divi Theme Builder 来显示每个专业人士的动态内容(使用高级自定义字段)。在每个专业人士的页面底部,我想添加一个 divi 博客模块,显示他们最近的 3 篇博文。这是我目前所拥有的 - 但页面上没有显示任何内容。
function add_author_recent_posts() {
$author = get_the_author(); // defines your author ID if it is on the post in question
$args = array(
'post_type' => 'professionals','post_status' => 'publish','author'=>$author,'posts_per_page' => 3,// the number of posts you'd like to show
'orderby' => 'date','order' => 'DESC'
);
$results = new WP_Query($args);
while ($results->have_posts()) {
$results->the_post();
the_title();
echo '</hr>'; // puts a horizontal line between results if necessary
}
}
add_action( 'init','add_author_recent_posts' );
解决方法
问题在于您调用 get_the_author 函数的位置。您已将其添加到 init
钩子上,此时,返回的作者将为 none:
function add_author_recent_posts() {
$author = get_the_author();
echo $author; die;
}
add_action( 'init','add_author_recent_posts' );
因此,我建议您将其置于 the_content
过滤器中,将您的帖子附加到原始内容中:
function add_author_recent_posts($content) {
$author = get_the_author();
$args = array(
'post_type' => 'post','post_status' => 'publish','author'=>$author,'posts_per_page' => 3,'orderby' => 'date','order' => 'DESC'
);
$results = new WP_Query($args);
while ($results->have_posts()) {
$results->the_post();
$content .= get_the_title();
$content .= '</hr>';
}
return $content;
}
add_filter( 'the_content','add_author_recent_posts' );