在Wordpress中,如何在侧边栏小部件中显示自定义帖子类型的单个随机帖子?

Cyn*_*hia 8 random wordpress sidebar widget custom-post-type

我为我正在研究的WP网站创建了一个自定义帖子类型 - Testimonials.我想在我的侧边栏中显示一个随机的推荐 - 如果可能的话,不使用插件.我是否需要使用正确的帖子查询创建文本小部件?如果是这样,它会是什么样子?

非常感谢,

辛西娅

The*_*pha 17

如果您愿意,可以直接将以下代码段粘贴sidebar.php到您要显示的位置Testimonials(确定是否为testimonials/Testimonials)

<?php
  $args = array(
    'post_type'=>'testimonials', 
    'orderby'=>'rand', 
    'posts_per_page'=>'1'
  );

  $testimonials=new WP_Query($args);

  while ($testimonials->have_posts()) : $testimonials->the_post(); 
?>
    <h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
    <p><?php the_excerpt(); // or the_content(); ?></p>
<?php 
  endwhile;
  wp_reset_postdata();
?>
Run Code Online (Sandbox Code Playgroud)