简体   繁体   English

将作者的 Wordpress 帖子网格(最新帖子)添加到自定义帖子类型

[英]Add a Wordpress post grid (latest posts) by author to a custom post type

I have created a custom post type called Professionals.我创建了一个名为 Professionals 的自定义帖子类型。 I am using the Divi Theme Builder to display each professional with their own dynamic content (using advanced custom fields).我正在使用 Divi Theme Builder 来显示每个专业人士都有自己的动态内容(使用高级自定义字段)。 At the bottom of each professional's page, I would like to add a divi blog module showing 3 of their most recent blog posts.在每个专业页面的底部,我想添加一个 divi 博客模块,显示他们最近的 3 篇博客文章。 Here's what I have so far - but nothing is showing on the page.这是我到目前为止所拥有的 - 但页面上没有显示任何内容。

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' );

The problem is where you're calling the get_the_author function.问题是你在哪里调用get_the_author function。 You've added it on init hook, and at this point, the Author returned will be none:您已将其添加到init钩子上,此时,返回的 Author 将是 none:

function add_author_recent_posts() {
    $author = get_the_author();
    echo $author; die;
}
add_action( 'init', 'add_author_recent_posts' );

So, I'll suggest you to place it on the_content filter, appending yours posts to the original content:因此,我建议您将其放在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' );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM