WordPress常用代码片段
2017-04-23 14:47
183 查看
1.显示所有文章分类:
2.截取指定长度和显示最新发布的文章标题:
在functions.php文件下定义my_sub_field方法:
3.显示相关页面链接:
4.显示某个分类目录下的最新文章:
如果要显示文章摘要添加代码:
5.显示同个父页面的其他子页面的链接:
假设有一个父页面,然后它有一些子页面。当打开父页面的时候,你想在 sidebar 显示它的子页面的链接。 当打开子页面链接的时候,你还是想要显示它同个父级下的所有一组链接。
<?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; ?>< a2ac /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>'; } ?>