在開發wordpress主題的時候,我們需要考慮到的一點是,訪客看完這篇文章后是不會直接就走掉的,而是會看看有沒有類似的或是相關的文章,如果這個時候我們在文章頁的底部或是側邊欄給訪客提供這些內容,就能讓訪客在網站里待的更久,大大降低跳出率,這樣對SEO也是很有好處的。
WP 文章調用方法,包括調用最新,指定分類,隨機,熱文等代碼,經測試(Muze也測試了下),支持當前最新版的WordPress,這里我把代碼記錄下來,方便自己日后查看,也給大家參考之用。
- 原文來源:詳情
調用最新文章
<?php query_posts('showposts=6&cat=-111'); ?> <!--顯示篇數和排除分類-->
<ul>
<?php while (have_posts()) : the_post(); ?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></li>
<?php endwhile;?>
</ul>
調用指定分類文章
<ul>
<?php
$args=array(
'cat' => 1, // 分類ID
'posts_per_page' => 10, // 顯示篇數
);
query_posts($args);
if(have_posts()) : while (have_posts()) : the_post();
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; endif; wp_reset_query(); ?>
</ul>
調用整站隨機文章
<ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand', 'post_status' => 'publish' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
</ul>
調用同分類隨機文章
<ul>
<?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();?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile;?>
<?php wp_reset_query(); ?>
</ul>
調用整站熱門文章(按評論數)
<ul>
<?php
$post_num = 10; // 顯示篇數
$args = array(
'post_password' => "",
'post_status' => 'publish', // 只選公開的文章.
'post__not_in' => array($post->ID),//排除當前文章
'caller_get_posts' => 1, // 排除置頂文章.
'orderby' => 'comment_count', // 依評論數排序.
'posts_per_page' => $post_num
);
$query_posts = new WP_Query();
$query_posts->query($args);
while( $query_posts->have_posts() ) { $query_posts->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php } wp_reset_query();?>
</ul>
但以上函數好像只能獲取到日志的標題和鏈接,如果能獲取到圖片就好了。
如果你還需要一些統計功能,那么還可以看看這篇wordpress開發文章:
如果只是想獲取上下文的相關信息的話,可以看看這篇文章: