為WordPress頁面(page)添加標簽和分類功能

WordPress的頁面(page)默認是不支援添加標簽和分類的,下面將分享下,讓頁面支援添加標簽和分類,以及在標簽存檔和分類存檔中包含頁面的方法。

post-tags-and-categories-for-pages-wpdaxue_com

要實現該功能,隻需下載安裝 Post Tags and Categories for Pages 外掛。或者你也可以將下面的代碼(來自該外掛)直接添加到當前主題的 functions.php 文件即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//為WordPress頁面添加標簽和分類
 
class PTCFP{
 
  function __construct(){
 
    add_action( 'init', array( $this, 'taxonomies_for_pages' ) );
 
    /**
     * 確保這些查詢修改不會作用於管理後臺,防止文章和頁面混雜 
     */
    if ( ! is_admin() ) {
      add_action( 'pre_get_posts', array( $this, 'category_archives' ) );
      add_action( 'pre_get_posts', array( $this, 'tags_archives' ) );
    } // ! is_admin
 
  } // __construct
 
  /**
   * 為“頁面”添加“標簽”和“分類”
   *
   * @uses register_taxonomy_for_object_type
   */
  function taxonomies_for_pages() {
      register_taxonomy_for_object_type( 'post_tag', 'page' );
      register_taxonomy_for_object_type( 'category', 'page' );
  } // taxonomies_for_pages
 
  /**
   * 在標簽存檔中包含“頁面”
   */
  function tags_archives( $wp_query ) {
 
    if ( $wp_query->get( 'tag' ) )
      $wp_query->set( 'post_type', 'any' );
 
  } // tags_archives
 
  /**
   * 在分類存檔中包含“頁面”
   */
  function category_archives( $wp_query ) {
 
    if ( $wp_query->get( 'category_name' ) || $wp_query->get( 'cat' ) )
      $wp_query->set( 'post_type', 'any' );
 
  } // category_archives
 
} // PTCFP
 
$ptcfp = new PTCFP();

//為WordPress頁面添加標簽和分類 class PTCFP{ function __construct(){ add_action( ‘init’, array( $this, ‘taxonomies_for_pages’ ) ); /**
* 確保這些查詢修改不會作用於管理後臺,防止文章和頁面混雜
*/
if ( ! is_admin() ) {
add_action( ‘pre_get_posts’, array( $this, ‘category_archives’ ) );
add_action( ‘pre_get_posts’, array( $this, ‘tags_archives’ ) );
} // ! is_admin } // __construct /**
* 為“頁面”添加“標簽”和“分類”
*
* @uses register_taxonomy_for_object_type
*/
function taxonomies_for_pages() {
register_taxonomy_for_object_type( ‘post_tag’, ‘page’ );
register_taxonomy_for_object_type( ‘category’, ‘page’ );
} // taxonomies_for_pages /**
* 在標簽存檔中包含“頁面”
*/
function tags_archives( $wp_query ) { if ( $wp_query->get( ‘tag’ ) )
$wp_query->set( ‘post_type’, ‘any’ ); } // tags_archives /**
* 在分類存檔中包含“頁面”
*/
function category_archives( $wp_query ) { if ( $wp_query->get( ‘category_name’ ) || $wp_query->get( ‘cat’ ) )
$wp_query->set( ‘post_type’, ‘any’ ); } // category_archives } // PTCFP $ptcfp = new PTCFP();

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *