wordpress调用随机文章的一些例子

作者:袖梨 2022-06-25

调用随机文章代码

<?php
$rand_posts = get_posts(‘numberposts=10&orderby=rand’);
foreach( $rand_posts as $post ) :
?>

”><?php the_title(); ?>
<?php endforeach; ?>

调用相关文章代码

在文章页显示相关文章

 代码如下 复制代码


<?php
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$first_tag = $tags[0]->term_id;
$args=array(‘
tag__in’ => array($first_tag),
‘post__not_in’ => array($post->ID),
‘showposts’=>10,
‘caller_get_posts’=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>

” rel=”bookmark” title=”<?php the_title_attribute(); ?>”><?php the_title();?> <?php comments_number(‘ ‘,’(1)’,’(%)’); ?>
<?php
endwhile;
}
}
wp_reset_query();
?>

调用同分类随机文章

将下面代码放到主题文章页面single模板或者边栏sidebar模板适当位置即可:

 代码如下 复制代码


  •     <?php

  •    $cat = get_the_category();

  •    foreach($cat as $key=>$category){

  •    $catid = $category->term_id;

  •    }

  •    $args = array('orderby' => 'rand','showposts' => 8,'cat' => $catid );

  •    $query_posts = new WP_Query();

  •    $query_posts->query($args);

  •     while ($query_posts->have_posts()) : $query_posts->the_post();

  •     ?>

  •    
  • <?php the_title(); ?>

  •     <?php endwhile;?>

相关文章

精彩推荐