您的位置:首页 > 编程语言

用WordPress短代码在侧栏小工具中调用不同分类的文章

2015-12-26 00:26 621 查看
本文介绍如何简单的在Wordpress主题中用短代码(shortcode)在侧栏的小工具里调用不同分类的若干最新文章。


在Wordpress主题functions.php中添加短代码

add_shortcode('slnet', 'slnet_shortcode');


在Wordpress主题functions.php中添加函数

function slnet_shortcode($atts, $content = null){   
    extract(shortcode_atts(array(    
        "slug"  => 'chengjiao',   
        //"title" => '最新文章',   
        //"num"   => '5',    
    ), $atts));   
    slnet_shortcode_base($slug,$title);   
}


extract() 函数用于解析短代码的属性并设置属性默认值,它的一个功能是把各个属性参数值赋给一个形如 “$参数名” 的变量保存起来(如上面例子中的 $slug ),该函数与 shortcode_atts() 配合可以很安全的输出结果。另外,它会将短代码中大写的属性值先转换为小写,再做为变量名使用,所以,短代码中的属性就别用大写了,为了提高效率,节约资源。

三个参数:分类slug、分类标题和调取的最新文章的数量,下面写出其它函数,显示调用内容的函数由于在具体的主题中使用,在css上有区别。


查询函数

//Custom shortcode for widget by Suoling.net 2013.11.11    
function coolwp_posts($query_text,$num) {   
    $slug = $query_text;   
    $icat=get_category_by_slug($slug);    
    $icat_links=get_category_link($icat->term_id);    
    $icat_name=$icat->name;      
    $cat_id=$icat->term_id;    
    return  query_posts("cat=($cata_id)&showposts=5&orderby=date&order=DESC");   
}


显示函数

function echo_posts($mytitle){   
    echo'<h5 class="widget_title">';   
    if(!(strlen($mytitle)==0)){   
        echo $mytitle;   
    }else{
        echo '问说网';
    }   
    echo'</h5><ul class="sl_latest_news_list">';   
    if (have_posts()) :
        while (have_posts()) : the_post();
            echo '<li class="sl-recent-post"><a href="';?><?php the_permalink();?><?php echo'" rel="bookmark" class="recent-post-title" title="'. get_the_title().'">'.get_the_title().'</a><span class="latest_posts_data">'?><?php the_time('Y-m-d');?><?php echo'</span></li>';   
        endwhile;
    endif;
    wp_reset_query();    
    echo '</ul>';   
}


上面的CSS需要你自己定义的哦!

判断一个字符串变量是否被传值,最好用其长度判断:
if(!(strlen($mytitle)==0)){      
    echo $mytitle;
}else{
    echo '最新文章';
}


上面的函数用作查询,下面的函数是短代码用的
function slnet_shortcode_base($myslug,$mytitle){
    coolwp_posts($myslug);
    echo_posts($mytitle);
}


在文本小工具中调用的短代码:
[slnet title="分类名称" slug="分类别名" num="调用多少篇最新文章"][/slnet]


顺便说一句,你要先确认你的主题的小工具是否支持短代码,如果不支持,请在主题的functions.php中添加如下hook:
add_filter('widget_text', 'do_shortcode');


本想把调用文章的数量也加上的,想一下,没什么必要,就不用了。后来,有对此函数做了修改,调用方式为:
[slnet  slug="分类别名"]分类名称[/slnet]


本文转载地址:http://www.uedsc.com/wordpress-sortcode-in-sidebar-widgetkit.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: