WordPress常用代碼片段

1.顯示所有文章分類:

<?php wp_list_categories( array("title_li" => "") ); ?>

2.截取指定長度和顯示最新發布的文章標題:

<?php
query_posts('showposts=10&orderby=new'); //showposts=10表示最多10篇
while(have_posts()): the_post();
?>
<li><a href="<?php the_permalink(); ?>"><?php my_sub_field(get_the_title(),10); ?></li>
<?php endwhile; ?>

在functions.php文件下定義my_sub_field方法:

/*截取某個字段的固定長度*/
function my_sub_field( $field, $len = 10 ){
//截取純文本摘要
$content = trim(strip_tags($field)); //去除HTML及PHP標籤
if( mb_strlen($content, 'utf-8') <= $len ){
$summary = $content;
}else{
$summary = mb_substr($content,0,$len,'utf-8'); //截取32個字符
$summary = $summary.'...';
}
echo $summary;
}

3.顯示相關頁面鏈接:

<?php
global $post;
if($post->post_parent){
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
$title = get_the_title($post->post_parent);
}else{
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
$title = $post->post_title;
}
if ($children) {
?>
<p><?php echo $title; ?></p>
<ul><?php echo $children; ?></ul>
<?php } ?>

4.顯示某個分類目錄下的最新文章:

<?php
query_posts('showposts=8&cat=2');
while(have_posts()) : the_post(); ?>
<li><a href="<?php the_permalink() ?>" target="_parent"><?php my_sub_field(get_the_title(),15); ?></a><span style="float:right;">[<?php the_time('Y-m-d'); ?>]</span></li>
<?php endwhile; ?>

如果要顯示文章摘要添加代碼:

<a href="<?php the_permalink() ?>"><?php my_sub_field(get_the_content(),120); ?></a>

5.顯示同個父頁面的其他子頁面的鏈接:

假設有一個父頁面,然後它有一些子頁面。當打開父頁面的時候,你想在 sidebar 顯示它的子頁面的鏈接。 當打開子頁面鏈接的時候,你還是想要顯示它同個父級下的所有一組鏈接。

<?php
global $post;
if($post->post_parent){
$children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0");
} else {
$children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0");
}
if ($children) {
echo '<ul>';
echo $children;
echo '</ul>';
}
?>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章