wordpress置顶自定义文章类型(sticky for custom post type)

wordpress默认的置顶功能很好用,但是只能在默认的“post”中使用,如何在自定义文章类型中添加置顶功能呢?

注意:本篇教程的自定义文章类型置顶功能经测试仅首页有效。

要置顶自定义文章类型,首先得在首页中显示自定义文章类型的文章,比如企业站中注册了一个名为product的产品文章类型,首先将产品显示在首页,参考:wordpress在首页显示或只显示自定义文章类型,或者在functions.php文件中加入下面代码,让首页只显示产品:

  1. function ashuwp_posts_per_page($query){
  2.   if ( is_home() )
  3.     $query->set( 'post_type', array( 'product' ) );
  4.   return $query;
  5. }
  6. add_action('pre_get_posts','ashuwp_posts_per_page');

方法:在文章编辑页面添加自定义字段。不管使用什么方法,请在后台文章编辑页面添加一个复选框checkbox,html结构如下即可:

  1. <input id="super-sticky" name="sticky" type="checkbox" value="sticky" /><label for="super-sticky" class="selectit">置顶</label>

上面代码中checkbox的name和value必须为sticky。

阿树做好的效果如图:

stickyposts

如何添加此自定义字段?阿树提供两种方法:

一、使用阿树工作室提供的后台框架阿树工作室---主题后台框架1.2

1. 阿树工作室提供的checkbox复选框是对应多个选项的,无法给checkbox使用一个固定的name,得新增加一个专门用于显示置顶字段的项。

编辑框架的meaboxclass.php文件,在类ashu_meta_box中增加一个方法,可加载checkbox函数附近,代码如下:

  1. function sticky($ashu_meta) {
  2.     $checked ="";
  3.     if( is_sticky() )
  4.       $checked = 'checked = "checked"';
  5.     echo '<input id="'.$ashu_meta['id'].'" name="sticky" type="checkbox" value="sticky"'. $checked.' /> <label for="super-sticky" class="selectit">'.$ashu_meta['name'].'</label>';
  6.   }

然后在框架的config.php文件中配置代码:

  1. /****product sticky******/
  2. $ashu_productinfo = array('title' => '置顶', 'id'=>'product_sticky', 'page'=>array('product'), 'context'=>'side', 'priority'=>'high', 'callback'=>'');
  3. $ashuwp_product_options[] = array(
  4.   'name'    => '置顶本产品',
  5.   'id'      => 'super-sticky',
  6.   'type'    => 'sticky'
  7. );
  8. $$ashu_productinfo_box = new ashu_meta_box($ashuwp_product_options,$ashu_productinfo);

二、直接在functions.php文件中添加如下代码,新增自定义字段面板:

  1. add_action( 'add_meta_boxes', 'ashuwp_add_product_box' );
  2. function ashuwp_add_product_box(){
  3.   add_meta_box( 'ashuwp_product_sticky', '置顶', 'ashuwp_product_sticky', 'product', 'side', 'high' );
  4. }
  5. function ashuwp_product_sticky (){ ?>
  6.   <input id="super-sticky" name="sticky" type="checkbox" value="sticky" <?php checked( is_sticky() ); ?> /><label for="super-sticky" class="selectit">置顶本产品</label>
  7. <?php
  8. }

添加完自定义面板,置顶功能即可用。

wordpress置顶自定义文章类型

已有7条评论

luxilang进行回复 取消回复