IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    轩枫阁V3主题开发-开发篇

    ivan发表于 2016-09-05 16:04:21
    love 0

    前言

    本文介绍关于轩枫阁V3主题开发内容,分为移动端和PC端。

    移动端

    针对移动端主题的开发处理主要有表格滚动条、纯文本简介、搜索标签、文件模块、loading加载、判断页面类型、微信图片预览等。

    表格处理

    文章里面的表格,经常宽度会大于移动设备屏幕的宽度,所以给表格加上滚动条尤为重要。

    WP在编辑文章插入表格时,会插入table标签,外层并没有特殊的class来标记含有表格,所以无法直接通过CSS的方式加上横向滚动条。

    1. JS判断表格,给外层加上指定Class。这种方法实现的会比较不友好。

    2. 通过PHP给table表格加上class

    // functions.php代码
    function table($content){
        if(!is_feed() || !is_robots) {
            $content = preg_replace('/<table(.*?)>(.*?)<\/table>/s', '<div class="table"><table$1>$2</table></div>', $content);
        }
        return $content;
    }
    // 文章内容
    add_filter('the_content', 'table');
    
    // CSS代码
    .table{
        overflow: auto;
        -webkit-overflow-scrolling: touch;  // 移动端流畅滚动
    }

    纯文本简介

    移动端的文章摘要为2行文字…,所以需要PHP输出纯文本。

    v3-desc

    // 获得纯文字简介
    function get_pure_expert($length=240){
        $content = get_the_content();
        $trimmed_content = wp_trim_words( $content, $length, '' );
        echo $trimmed_content;
    }
    add_filter('get_pure_expert', 'get_pure_expert');
    
    // 模版中使用
    <?php get_pure_expert(160);?>

    搜索标签

    移动端的搜索页面,点击搜索框后,会在页面随机显示标签,可点击标签搜索。

    h5-search

    // JS获取标签
    $.ajax({
        url: 'http://www.xuanfengge.com/?action=tag',
        type: 'get',
        beforeSend: function() {},
        error: function(error) {},
        success: function(data) {
            tagList.html($(data));
        }
    });
    
    // PHP代码 functions.php
    // 输出标签
    function tagLoad(){
        if(isset($_GET['action'])){
            if($_GET['action'] == 'tag'){
                echo wp_tag_cloud('smallest=14&largest=14&unit=px&number=32&order=RAND');
                die;
            }
        }
    }
    add_action('init', 'tagLoad');

    文件模块

    WP中,除了可以<?php get_header();?>引入header.php文件之外,对于公用的小文件模块,可以单独命名并引入。

    如上面的标签搜索页面,在WP的文件中是没有的,但是很多页面都需要引入,这时候可以命名为search-index.php,通过get_template_part方式引入。

    <?php get_template_part('category', 'list');?>

    loading加载

    关于文章列表的loading,在页面滚动到底部的时候,需要显示loading,同时加载下一页文章。

    由于移动端是在滚动缓冲停止后才会触发scroll,使得loading是不是及时的出现,有一定的延时。

    换一种思路实现,即loading为一直显示,当有下一页内容返回,插入到页面底部,同时loading被挤到最后;如果没有下一页,则将loading移除。

    判断页面类型

    由于JS代码不多,所以将JS文件合并成一个文件。不同页面都适用同一个js,有些功能并不需要触发,所以需要PHP提供当前页面类型给JS读取。

    <script>
    window.blog = {
        is_home: '<?php echo is_home();?>',
        is_category: '<?php echo is_category();?>',
        is_single: '<?php echo is_single();?>',
        is_search: '<?php echo is_search();?>',
        is_tag: '<?php echo is_tag();?>',
        is_local: false
    }
    </script>

    微信图片预览

    移动端的文章,如果分享到微信,在微信中阅读的时候,可以使用微信提供的JSSDK,imagePreview实现预览大图。预览图片这个功能并不需要wx.config注册。如果有使用到分享功能,则需要注册订阅号或企业号签名。

    PC端

    针对PC版主题的开发主要处理文章链接新窗口打开、分享、赞赏、查看大图、文章导航、钢琴导航、返回顶部、友情链接、文章列表分页等内容。

    文章链接新窗口打开

    在阅读文章的时候,文章里的链接在新窗口中打开才是合理的。而在编辑文章的时候,往往可能会漏掉勾选在新窗口中打开,所以可以通过PHP来实现。

    同时对于外链,最好同时加上rel=”nofollow”告诉搜索引擎无需追踪目标页,防止恶意链接给博客带来降权。

    //为文章中所有链接添加target="_blank"属性
    function autoblank($content) {
        $content = preg_replace("/<a(.*?)>/", "<a$1 target=\"_blank\">", $content);
        return $content;
    }
    add_filter('the_content', 'autoblank');
    
    // 文章外部链接加上rel="nofollow"
    function cn_nf_url_parse($content) {
    
        $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>";
        if(preg_match_all("/$regexp/siU", $content, $matches, PREG_SET_ORDER)) {
            if( !empty($matches) ) {
    
                $srcUrl = get_option('siteurl');
                for ($i=0; $i < count($matches); $i++){
    
                    $tag = $matches[$i][0];
                    $tag2 = $matches[$i][0];
                    $url = $matches[$i][0];
    
                    $noFollow = '';
    
                    $pattern = '/target\s*=\s*"\s*_blank\s*"/';
                    preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
                    if( count($match) < 1 )
                        $noFollow .= ' target="_blank" ';
    
                        $pattern = '/rel\s*=\s*"\s*[n|d]ofollow\s*"/';
                        preg_match($pattern, $tag2, $match, PREG_OFFSET_CAPTURE);
                    if( count($match) < 1 )
                        $noFollow .= ' rel="nofollow" ';
    
                        $pos = strpos($url,$srcUrl);
                    if ($pos === false) {
                        $tag = rtrim ($tag,'>');
                        $tag .= $noFollow.'>';
                        $content = str_replace($tag2,$tag,$content);
                    }
                }
            }
        }
    
        $content = str_replace(']]>', ']]>', $content);
        return $content;
    }
    add_filter( 'the_content', 'cn_nf_url_parse');

    分享

    对于分享,本站支持微博、微信二维码、空间、腾讯微博、人人网,实现代码参考本站介绍:社交平台分享自定义javascript组件

    v3-share

    赞赏

    新增赞赏功能,可以使用微信支付打赏作者。

    v3-reward

    v3-rewards

    查看大图

    文章页查看大图,之前是使用的wp-lightbox2插件,使用简单方便。但是为了减少使用的插件,这里自己开发了查看大图的功能。

    功能:图片垂直居中显示、点击图片左半部分切换上一张、点击图片左半部分切换下一张、点击遮罩层或关闭按钮关闭、显示当前预览进度、可以下载原图、图片不能超过屏幕可显示范围。

    pc-lightbox

    // HTML代码
    <div class="js_lightbox mod-lightbox ui-d-n animated short fadeIn">
        <div class="js_lightbox_content mod-lightbox__box"></div>
        <div class="js_lightbox_overlay mod-lightbox__overlay"></div>
        <div class="js_lightbox_close mod-lightbox__close" title="关闭"></div>
    </div>
    
    <script type="text/html" id="js_lightbox_tpl">
        <img src="{{src}}" style="width: {{width}}px;height: {{height}}px;" alt="" class=" animated short fadeIn">
        <div class="mod-lightbox__nav">
            {{if index > 1}}
            <a href="javascript:;" class="js_lightbox_prev mod-lightbox__prev"></a>
            {{/if}}
            {{if index < total}}
            <a href="javascript:;" class="js_lightbox_next mod-lightbox__next"></a>
            {{/if}}
        </div>
        <div class="mod-lightbox__info">
            <span class="">{{index}}</span> / <span class="">{{total}}</span>
            <a href="{{src}}" class="mod-lightbox__link" target="_blank">查看原图</a>
        </div>
    </script>
    
    
    // JS代码
    // 这里有使用到atrTemplate.js模版引擎
    function Lightbox(options){
        this.$article = $('.js_single');
        this.$lightbox = $('.js_lightbox');
        this.tpl = template.compile($('#js_lightbox_tpl').html());
        this.imgList = $('.js_article_content').find('img');
        this.listenEvents();
    }
    
    Lightbox.prototype = {
        listenEvents: function(){
            var self = this;
            this.$article.on('click', 'a, img', function(event){
                var target = $(this);
                if(target.parent().is('a') || target.is('img')){
                    var img = target.is('img') ? target : target.parent();
                    var index = self.imgList.index(img)+1;
                    self.showLightbox(index);
                    return false;
                }
            });
    
            this.$article.on('click', '.js_lightbox_prev', function(event){
                var index = self.currentIndex - 1;
                self.showLightbox(index);
            });
            this.$article.on('click', '.js_lightbox_next', function(event){
                var index = self.currentIndex + 1;
                self.showLightbox(index);
            });
    
            $('.js_lightbox_close, .js_lightbox_overlay').on('click', function(){
                self.hideLightbox();
            });
        },
    
        showLightbox: function(index){
            this.currentIndex = index;
    
            var img = this.imgList.eq(index-1);
            var src = img.data('original');
            var width = img.attr('width') || img.width();
            var height = img.attr('height') || img.height();
            var winHeight = $win.height()-50;
            var winWidth = $win.width()-20;
    
            // 计算图片宽度
            if(winHeight < height){
                width = parseInt(winHeight*width/height);
                height = winHeight;
            }else if(winWidth < width){
                width = winWidth;
                height = winHeight;
            }
    
            $('.js_lightbox_content').html(this.tpl({
                src: src,
                index: index,
                width: width,
                height: height,
                total: this.imgList.length
            }));
            if(!this.$lightbox.is(':visible')){
                this.$lightbox.show();
            }
            $body.addClass('ovh');  // 隐藏滚动条
        },
    
        hideLightbox: function(){
            this.$lightbox.hide();
            $body.removeClass('ovh');
        }
    }
    
    // 初始化(在文章页)
    var lightbox = new Lightbox();

    文章导航

    具体实现方式参考文章介绍:wordpress自动生成文章目录

    v3-menu

    钢琴导航

    介绍:钢琴节奏

    Github:piano-play

    返回顶部

    返回顶部这里结合CSS3,做出纸飞机起飞的动画。

    scrolltop

    友情链接

    侧边栏的友情链接,之前是写在sidebar.php文件里,又更新需要上线代码。V3主题改为在WP后台配置,代码读取的方式,相对灵活。

    add_action('admin_init', 'wpjam_blogroll_settings_api_init');
    function wpjam_blogroll_settings_api_init() {
        add_settings_field('wpjam_blogroll_setting', '友情链接', 'wpjam_blogroll_setting_callback_function', 'reading');
        register_setting('reading','wpjam_blogroll_setting');
    }
    
    function wpjam_blogroll_setting_callback_function() {
        echo '<textarea name="wpjam_blogroll_setting" rows="10" cols="50" id="wpjam_blogroll_setting" class="large-text code">' . get_option('wpjam_blogroll_setting') . '</textarea>';
    }
    
    function wpjam_blogroll(){
        $wpjam_blogroll_setting =  get_option('wpjam_blogroll_setting');
        if($wpjam_blogroll_setting){
            $wpjam_blogrolls = explode("\n", $wpjam_blogroll_setting);
            foreach ($wpjam_blogrolls as $wpjam_blogroll) {
                $wpjam_blogroll = explode("|", $wpjam_blogroll );
                echo '<li><a href="'.trim($wpjam_blogroll[0]).'" title="'.esc_attr(trim($wpjam_blogroll[1])).'">'.trim($wpjam_blogroll[1]).'</a></li>';
            }
        }
    }

     

    文章列表分页

    之前的分页实现方式为使用wp-pagenavi插件,为了减少插件的使用,更改为代码实现分页的方式。

    v3-pagenavi

    // 分页
    function par_pagenavi($range = 9){
        global $paged, $wp_query;
        if ( !$max_page ) {
            $max_page = $wp_query->max_num_pages;
        }
        if($max_page > 1){
            if(!$paged){
                $paged = 1;
            }
            if($paged != 1){
                echo "<a href='" . get_pagenum_link(1) . "' class='first' title=''>&lt;&lt;</a>";
            }
            previous_posts_link('←');
            if($max_page > $range){
                if($paged < $range){
                    for($i = 1; $i <= ($range + 1); $i++){
                        if($i==$paged){
                            echo "<span class='current'>$i</span>";
                        }else{
                            echo "<a href='" . get_pagenum_link($i) ."'>$i</a>";
                        }
                    }
                }
                elseif($paged >= ($max_page - ceil(($range/2)))){
                    for($i = $max_page - $range; $i <= $max_page; $i++){
                        if($i==$paged){
                            echo "<span class='current'>$i</span>";
                        }else{
                            echo "<a href='" . get_pagenum_link($i) ."'>$i</a>";
                        }
                    }
                }
                elseif($paged >= $range && $paged < ($max_page - ceil(($range/2)))){
                    for($i = ($paged - ceil($range/2)); $i <= ($paged + ceil(($range/2))); $i++){
                        if($i==$paged){
                            echo "<span class='current'>$i</span>";
                        }else{
                            echo "<a href='" . get_pagenum_link($i) ."'>$i</a>";
                        }
                    }
                }
            }else{
                for($i = 1; $i <= $max_page; $i++){
                    if($i==$paged){
                        echo "<span class='current'>$i</span>";
                    }else{
                        echo "<a href='" . get_pagenum_link($i) ."'>$i</a>";
                    }
                }
            }
            next_posts_link('→');
            if($paged != $max_page){
                echo "<a href='" . get_pagenum_link($max_page) . "' class='last'>&gt;&gt;</a>";
            }
        }
    }
    
    
    // 使用
    <?php par_pagenavi(4); ?>



沪ICP备19023445号-2号
友情链接