查看目录
最近看到很多网站文章有一个点击阅读全文按钮,在内容比较多的情况下添加了展开收缩功能,很是美观,而且对于用户体验和SEO优化都有好处。学习了一下,经过测试多次之后整理纯代码添加wordpress展开收缩功能步骤如下。

一、wordpress展开收缩功能JS代码:
// 添加文章页展开收缩JS效果
<script type="text/javascript">
jQuery(document).ready(
function(jQuery){
jQuery('.collapseButton').click(
function(){
jQuery(this).parent().parent().find('.xContent').slideToggle('slow');
}
);
}
);
</script>
此JS代码我们可以添加到网站的头部文件(header.php)里面单独应用,亦可以添加到wordpress主题的整体JS里面,比如本站主题就可以添加到“Js/libs/html5.min.js”。如果要添加到js文件中时,记得把前后的<script></script>去掉。
二、wordpress展开收缩功能代码
添加以下代码到wordpress主题文件的“functions.php”中。
//展开收缩功能 chukuangren.com
function xcollapse($atts, $content = null){
extract(shortcode_atts(array("title"=>""),$atts));
return '<div style="margin: 0.5em 0;">
<div class="xControl">
<span class="xTitle">'.$title.'</span><i class="fa fa-plus-square" aria-hidden="true"></i>
<a href="javascript:void(0)" class="collapseButton xButton">阅读全文</a>
<div style="clear: both;"></div>
</div>
<div class="xContent" style="display: none;">'.$content.'</div>
</div>';
}
add_shortcode('collapse', 'xcollapse');
二、展开收缩功能短代码插入
在我们编辑文章过程中,需要添加“点击阅读全文”的位置,添加短代码
【collapse title="展开收缩"】阅读全文【/collapse】
实际使用时,记得把【】切换成[]。
为了方便插入,我们还可以把wordpress展开收缩功能做成一个按钮加入到编辑器里面,这样使用更简单。呃,同样的,大家使用代码时,记得把里面的【】成[]。
//编辑器插入展开收缩按钮
function appthemes_add_collapse() {
?>
<script type="text/javascript">
if ( typeof QTags != 'undefined' ) {
QTags.addButton( 'collapse', '展开收缩按钮', '【collapse title="展开"】','【/collapse】' );
}
</script>
<?php
}
add_action('admin_print_footer_scripts', 'appthemes_add_collapse' );
这样我们编辑文章时可以在适当的位置添加“展开收缩按钮”,需要注意的是,此按钮两次组合为一个完整的短代码,所以我们在文章中间添加一次,文章结束之后再添加一次,这样才能完美的实现文章内容收缩,点击阅读全文的功能。
另外,有的wordpress主题会有一个“jQuery底部加载”的选项,记得取消这个功能,否则展开收缩阅读全文的JS加载不了,就会不显示隐藏内容。
效果演示:
展开查看全文…
楚狂人




