【问题标题】:Modify code to display more than one blurb修改代码以显示多个简介
【发布时间】:2016-03-09 15:08:42
【问题描述】:

下面的代码是一个 WordPress 书店网站,它在每个书页上输出关于作者的简介,从相应的作者页面中提取内容。它在大多数情况下都可以正常工作,除非有多个作者,它只显示一个作者(有时不显示主要作者)。

有没有办法修改它,如果有多个作者,它会显示所有作者的简介?

谢谢!

<?php if ( is_single() ) { ?>
<div class="featured-author">
  <div class="widget widget_lpcode">
     <h2 class="widget-title">About the Author</h2>
     <div class="textwidget">
        <?php
           $authors = array();
           $parents = array(
               'Author' => 35
           );
           $categories = get_the_terms( $post->ID, 'product_cat' );
           foreach( $parents as $parent_name => $parent_id ):
               foreach( $categories as $category ):
                   if( $parent_id == $category->parent ):
                       $authors[] = $category->slug;
                   endif;
               endforeach;
           endforeach;

           $custom_query = new WP_Query( array( 'post_type' => 'authors','post_name__in' => $authors,'posts_per_page' => '-1' ) );  

           if($custom_query->have_posts()) : 
                while($custom_query->have_posts()) : 
                   $custom_query->the_post();
           ?>
        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
           <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a>
           <header class="entry-header">
              <h1 class="entry-title"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h1>
           </header>
           <div class="entry-content">
              <p><?php get_the_content_limit(115, ''); ?></p>
              <p><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>" class="more">More</a></p>
           </div>
        </article>
        <?php
           endwhile;
           else: 
           ?>
        Not Found.
        <?php
           endif;
           ?>
     </div>
  </div>
</div>

【问题讨论】:

    标签: php wordpress custom-post-type


    【解决方案1】:

    您当前正在循环遍历每个类别,然后将相同的 $author 变量分配给该类别的 slug,因此如果有多个类别,您每次只需覆盖该 $author 变量,它最终将等于最后的结果。

    首先,建立一个空白作者数组:

    $authors = array();

    然后,在你的 foreach 循环中,将结果添加到该数组中:

    $authors[] = $category-&gt;slug;

    最后,在您的 $custom_query WP_Query 参数中,您需要更改查找帖子的方式,因为“名称”参数只接受一个 slug。在 WP 4.4 中有一个新的post_name__in 参数接受一个数组,所以你可以使用

    'post_name__in' =&gt; $authors,

    如果您不能使用 WP 4.4,则必须在作者数组中获取每个帖子的 ID,然后使用接受 ID 数组的post__in 参数。

    另外,将“posts_per_page”参数从 1 更改为 -1,以便显示所有结果。

    【讨论】:

    • 哇,效果很好。谢谢@johnnyd23!我已经用正确的代码更新了我的问题(适用于 WP 4.4)。
    猜你喜欢
    • 1970-01-01
    • 2015-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2011-10-05
    相关资源
    最近更新 更多