一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

wordpress 文章首页置顶实现例子

时间:2016-06-17 编辑:简简单单 来源:一聚教程网

wordpress置顶的数据保存在options表的option_name等于sticky_posts,option_value的字段中。数据经过了序号化之后保存的,即使用php函数serialize

在wordpress里调取方法

$sticky = get_option(‘sticky_posts’);

目前的首页置顶的代码
目前我的首页置顶代码如下,我感觉很多模板都会有这个问题

 代码如下复制代码

$sticky = get_option('sticky_posts'); rsort( $sticky );
query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1, 'showposts' => 4 ) );


上面的代码的问题分析

sql使用in的方式查询,如果置顶的文章越多,$sticky变量数据就会越多,查询的速度越慢。目前阶段数据量少感觉不出来,之后数据多了,查询会变慢很多

优化首页置顶的代码如下

  

 代码如下复制代码
  $sticky = get_option('sticky_posts'); rsort( $sticky );
    if(is_array($sticky)){
        $num=count($sticky);
        if($num>4){
            $num=4;
        }
        $sticky=array_slice($sticky,0,$num);
    }
    query_posts( array( 'post__in' => $sticky, 'caller_get_posts' => 1, 'showposts' => 4 ) );

原理其实是把get_option('sticky_posts')调出来的数组去4个,然后在去用in查询

热门栏目