有時我們在開發wordpress時需要調用置頂文章sticky_posts,怎麼調用呢?幾種寫法,有用到query_post的,有用到WP_Query,也有用到is_sticky(),下面随ytkah一起來看看吧
第一種調用置頂文章的方法,用到query_post,代碼如下
<?php
$query_post = array(
'posts_per_page' => 10,
'post__in' => get_option('sticky_posts'),
'caller_get_posts' => 1
);
query_posts($query_post);
?>
<?php while(have_posts()):the_post(); ?>
<div class="swiper-slide">
<a href="<?php the_permalink(); ?>">
<img src="<?php the_post_thumbnail_url( 'full' ); ?>" alt="<?php the_title(); ?>">
<div class="shadow">
<?php the_title(); ?>
</div>
</a>
</div>
<?php endwhile; ?>
<?php
wp_reset_query();
?>
參數用一個數組的形式放在
$query_post
中,關鍵的參數為'post__in' =>get_option('sticky_posts')和'caller_get_posts' => 0。
'post__in' => get_option('sticky_posts')确定了該 LOOP 調用的是置頂文章清單。
'caller_get_posts'的作用是排除非指定性文章,即除了置頂文章之外,不顯示其他的文章。
'posts_per_page' => 10,控制文章的數量
不添加的情況下,如果置頂文章條目不足'posts_per_page'規定的值,會用最新文章替補完整。
如果想調用除了置頂文章外的本欄目其餘所有文章怎麼操作?
<?php
$query_post = array(
'category__in' => array(get_query_var('cat')),//如果是欄目調用,注意這行要加,否則會調用全站所有文章
'posts_per_page' => 5,
'post__not_in' => get_option('sticky_posts'),//排除置頂
'caller_get_posts' => 1
);
query_posts($query_post);
?>
<?php while(have_posts()):the_post(); ?>
<div class="item wow zoomIn">
<div class="img-box">
<img src="<?php the_post_thumbnail_url( 'full' ); ?>" alt="<?php the_title(); ?>">
</div>
<div class="text">
<div class="title">
<h3>
<?php the_title(); ?>
</h3>
</div>
<div class="description">
<p>
<?php the_excerpt(); ?>
</p>
</div>
<div class="more">
<a href="<?php the_permalink(); ?>">Read More</a>
</div>
</div>
</div>
<?php endwhile; ?>
<?php
wp_reset_query();
?>
第二種寫法用到WP_Query,和第一種方法有點類似,代碼如下
<?php
$args = array(
'posts_per_page' => -1,
'post__in' => get_option( 'sticky_posts' )
);
$sticky_posts = new WP_Query( $args );
while ( $sticky_posts->have_posts() ) : $sticky_posts->the_post();?>
<li>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; wp_reset_query();?>
第三種方法,用is_sticky()判斷
<?php if (have_posts()) : ?>
<p>文章清單如下</p>
<ul>
<?php while (have_posts()) : the_post();
if (is_sticky()):
global $more; // 設定全局變量$more
$more = 1;
?>
<li>
<h2>[置頂]<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" rel="bookmark"><?php the_title(); ?></a><h2/>
<p><?php the_content(); ?></p>
</li>
<?php else:
global $more;
$more = 0;
?>
<li>
<h2><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" rel="bookmark"><?php the_title(); ?></a><h2/>
<p><?php the_content('閱讀更多'); ?></p>
</li>
<?php endif; ?>
<?php endwhile; ?>
</ul>
<?php else: ?>
<h2>沒有找到更多文章</h2>
<?php endif; ?>
關于置頂文章wordpress有兩個常用的函數
is_sticky():判斷文章是否是置頂的,是就傳回true,不是就傳回false
get_option('sticky_posts'): 擷取置頂文章ID,傳回包含各置頂文章ID的數組
首頁展示文章時,如果是置頂文章就全文輸出
方法簡介:在loop循環時,通過
is_sticky()
判斷是否是置頂文章
是的話就設定全局變量$more=1;然後調用
the_content()
;就是全文輸出了
否則不是置頂文章的話就設定全局變量 $more=0;然後調用 the_content('更多...');就是截取<--more-->标簽後的輸出
以上三種方法可以靈活運用,祝大夥開發愉快!
參考資料https://developer.wordpress.org/reference/classes/wp_query/