【问题标题】:Add a Wordpress post grid (latest posts) by author to a custom post type将作者的 Wordpress 帖子网格(最新帖子)添加到自定义帖子类型
【发布时间】:2021-03-02 20:49:55
【问题描述】:

我创建了一个名为 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' );

【问题讨论】:

    标签: wordpress module blogs author divi


    【解决方案1】:

    问题在于您调用get_the_author 函数的位置。您已将其添加到 init 钩子上,此时返回的 Author 将为无:

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

    【讨论】:

      猜你喜欢
      • 2011-11-19
      • 1970-01-01
      • 2016-11-29
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多