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 。

阿樹做好的效果如圖:

如何新增此自定義欄位?阿樹提供兩種方法:

一、使用阿樹工作室提供的後臺框架阿樹工作室---主題後臺框架 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. }

新增完自定義面板,置頂功能即可用。