簡體   English   中英

如何在WP中為自定義帖子類型設置默認分類法(類別)

[英]How to set default taxonomy (category) for custom post types in WP

我已閱讀完所有可以找到的博客文章,但似乎沒有任何內容適合我。 我需要做的就是讓WP自動為我的自定義帖子類型“照片”分配默認分類法/類別(“最新”),以便在用戶添加新照片時,已經選擇了“最新”類別,分配(例如,對於普通博客文章的“未分類”)。

declare ( encoding = 'UTF-8' );

! defined( 'ABSPATH' ) and exit;

add_action( 'init', array ( 'MCP_Photos', 'init' ) );

class MCP_Photos
{
    /**
     * Creates a new instance.
     * 
     * @wp-hook init
     * @see    __construct()
     * @return void
     */
    public static function init()
    {
        new self;
    }

    /**
     * Constructor
     */
    public function __construct()
    {
      $labels = array(
    'name' => 'Photography',
    'singular_name' => 'Photo',
    'add_new' => 'Add New',
    'add_new_item' => 'Add New Photo',
    'edit_item' => 'Edit Photo',
    'new_item' => 'New Photo',
    'all_items' => 'All Photos',
    'view_item' => 'View Photo',
    'search_items' => 'Search Photos',
    'not_found' =>  'No Photos found',
    'not_found_in_trash' => 'No Photos found in Trash', 
    'parent_item_colon' => '',
    'menu_name' => 'Photography'
  );

        $args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true, 
    'show_in_menu' => true, 
    'query_var' => true,
            'rewrite' => array(
                'with_front' => false,
                'slug' => "photo"
            ),
     'capability_type' => 'post',
    'has_archive' => true, 
    'hierarchical' => true,
    'menu_position' => null,
    'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
    'taxonomies' => array('post_tag')
        );
        register_post_type("photos", $args);

        // Prevent WordPress from sending a 404 for our new perma structure.
        add_rewrite_rule(
        '^photo/(\d+)/[^/]+/?$',
        'index.php?post_type=photos&p=$matches[1]',
        'top'
        );

        // Inject our custom structure.
        add_filter( 'post_type_link', array ( $this, 'fix_permalink' ), 1, 2 );
    }

    /**
     * Filter permalink construction.
     * 
     * @wp-hook post_type_link
     * @param  string $post_link default link.
     * @param  int    $id Post ID
     * @return string
     */
    public function fix_permalink( $post_link, $id = 0 )
    {
        $post = &get_post($id);
        if ( is_wp_error($post) || $post->post_type != 'photos' )
        {
            return $post_link;
        }
        // preview
        empty ( $post->slug )
            and $post->slug = sanitize_title_with_dashes( $post->post_title );

        return home_url(
            user_trailingslashit( "photo/$post->ID/$post->slug" )
        );
    }
}



// ----------------------------- add photography categories taxonomy ---------------------------------- 


function create_photo_categories() {
    register_taxonomy(
        'photography', // name of the taxonomy
        'photos', // for which post type it applies
        array(
            'labels' => array(
                'name' => 'Categories',
                'add_new_item' => 'Add New Category',
                'new_item_name' => "New Category"
            ),
            'show_ui' => true,
            'show_tagcloud' => false,
            'hierarchical' => true
        )
    );
}

add_action( 'init', 'create_photo_categories', 0 );

我只是發現了這個舊問題,沒有正確而完整的答案。 因此,我正在將其寫給對此主題感興趣的任何人。

我將詳細解釋:

如何注冊CPT和自定義分類法並添加默認條款(不可刪除)

當沒有通過CPT metabox選擇其他術語時,如何將該默認術語注冊到我們的自定義帖子類型中。

進行步驟:

  1. 初始化后,您需要使用register_post_type函數注冊您的CPT。
  2. 注冊CPT后,使用register_taxonomy函數注冊自定義分類法。
  3. 注冊后將術語添加到自定義分類中。
  4. 為分類法設置默認術語。
  5. 保存后將默認術語添加到CPT。

注意:我已經更改了問題中呈現的代碼的結構,並使用了單例方法,並刪除了該問題的特定部分(例如,重寫規則等)。我還將CPT名稱更改為photo ,分類名稱更改為gallery_cat ,默認術語為slug到default_gallery_cat

重要說明: default_{$taxonomy}選項用於將默認類別設置為不可移動,例如默認uncategorized WP類別

注意:您只能分配一個術語作為默認分類術語。

我在代碼中寫了其他細節作為注釋。 它是一個功能正常的WP插件。

最終代碼:

<?php
/*
 Plugin Name: Sample CPT Default Taxonomy
 Plugin URI: http://www.yashar.site/
 Description: A sample plugin to register Photo CPT and gallery_cat custom taxonomy and add a default category.
 Version: 1.0
 Author: Yashar Hosseinpour
 Author URI: http://www.yashar.site/
 */

namespace My_Plugin;

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class Photo
{
    /**
     * Instance of Photo
     * @access protected
     * @var object $instance The instance of Photo.
     */
    private static $instance = null;

    /**
     * Photo constructor.
     * This is a private constructor to be used in getInstance method to do things in a singleton way
     * It's a good idea to leave this constructor empty and make `init` method public to use it outside of the class, which is a good thing for Unit Testing
     * @access private
     */
    private function __construct()
    {
        $this->init();
    }

    /**
     * Initialize the plugin.
     * You can make it public and use it outside of the class
     * @access private
     * @return void
     */
    private function init()
    {
        // It's possible to use one method to cover these and hook it to `init`. I just like the way using single purpose OOP methods.
        // Note the priorities
        add_action('init', [$this, 'register_cpt'], 10);
        add_action('init', [$this, 'register_gallery_cat_tax'], 11);
        add_action('init', [$this, 'insert_default_gallery_cat_term' ], 12);

        // `save_post_{$post->post_type}` hook is used. Doc: https://developer.wordpress.org/reference/hooks/save_post_post-post_type/
        add_action( 'save_post_photo', [$this, 'set_default_gallery_cat'], 99, 2 );
    }

    /**
     * Register `Photo` CPT and `gallery_cat` taxonomy to it
     * This should be done after `init`
     * @access public
     * @wp-hook init
     * @return void
     */
    public function register_cpt()
    {
        $labels = array(
            'name' => 'Photos',
            'singular_name' => 'Photo',
            'add_new' => 'Add New',
            'add_new_item' => 'Add New Photo',
            'edit_item' => 'Edit Photo',
            'new_item' => 'New Photo',
            'all_items' => 'All Photos',
            'view_item' => 'View Photo',
            'search_items' => 'Search Photos',
            'not_found' =>  'No Photos found',
            'not_found_in_trash' => 'No Photos found in Trash',
            'parent_item_colon' => '',
            'menu_name' => 'Photography'
        );
        $args = array(
            'public' => true,
            'show_in_menu' => true,
            'labels' => $labels,
            'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' ),
            'taxonomies' => array('post_tag', 'gallery_cat')
        );
        register_post_type('photo', $args);
    }

    /**
     * Register `gallery_cat` taxonomy
     * This should be done after registering CPT
     * @access public
     * @wp-hook init
     * @return void
     */
    public function register_gallery_cat_tax() {
        $labels = [
            'name'                      =>  'Gallery Categories',
            'singular_name'             =>  'Gallery Category',
            'all_items'                 =>  'All Gallery Categories',
            'edit_item'                 =>  'Edit Category',
            'view_item'                 =>  'View Category',
            'update_item'               =>  'Update Category',
            'add_new_item'              =>  'Add New Category',
            'new_item_name'             =>  'Category Name',
            'parent_item'               =>  'Parent Category',
            'parent_item_colon'         =>  'Parent Category:',
            'search_items'              =>  'Search Gallery Categories',
            'popular_items'             =>  'Popular Categories',
        ];
        register_taxonomy(
            'gallery_cat',
            'photo',
            array(
                'labels' => $labels,
                'show_ui' => true,
                'show_tagcloud' => false,
                'hierarchical' => true
            )
        );
    }

    /**
     * Insert default gallery_cat
     * `default_{$taxonomy}` option is used to make this term as default `gallery_cat` term (non-removable)
     * @access public
     * @wp-hook init
     */
    public function insert_default_gallery_cat_term()
    {
        // check if category(term) exists
        $cat_exists = term_exists('default_gallery_cat', 'gallery_cat');

        if ( !$cat_exists ) {
            // if term is not exist, insert it
            $new_cat = wp_insert_term(
                'Default Gallery Name',
                'gallery_cat',
                array(
                    'description'   =>  'This is your default gallery category',
                    'slug'          =>  'default_gallery_cat',
                )
            );
            // wp_insert_term returns an array on success so we need to get the term_id from it
            $default_cat_id = ($new_cat && is_array($new_cat)) ? $new_cat['term_id'] : false;
        } else {
            //if default category is already inserted, term_exists will return it's term_id
            $default_cat_id = $cat_exists;
        }

        // Setting default_{$taxonomy} option value as our default term_id to make them default and non-removable (like default uncategorized WP category)
        $stored_default_cat = get_option( 'default_gallery_cat' );

        if ( empty( $stored_default_cat ) && $default_cat_id )
            update_option( 'default_gallery_cat', $default_cat_id );
    }

    /**
     * Add an default `gallery_cat` taxonomy term for `photo` CPT on save
     * If no `gallery_cat` is selected, default gallery_cat will be registered to the post
     * @access public
     * @wp-hook save_post_photo
     * @param integer $post_id
     * @param object $post
     */
    public function set_default_gallery_cat($post_id, $post)
    {
        if ( 'publish' === $post->post_status ) {
            $gallery_cats = wp_get_post_terms( $post_id, 'gallery_cat' );
            $default_gallery_cat = (int) get_option('default_gallery_cat');

            if ( empty($gallery_cats) ) {
                wp_set_object_terms( $post_id, $default_gallery_cat, 'gallery_cat' );
            }
        }
    }

    /**
     * Instance
     * Used to retrieve the instance of this class.
     * @access public
     * @return object $instance of the class
     */
    static public function getInstance() {
        if (self::$instance == NULL) {
            self::$instance = new self();
        }
        return self::$instance;
    }
}

// Run this
Photo::getInstance();

經過全面測試,可在WP 5.1上運行

注意: save_post _ {$ post-> post_type}鈎子用於在保存photo CPT時添加默認類別術語。

請注意,我已經使用init鈎子注冊了東西,但是如果您在多站點WP安裝中,則可以考慮使用wp_loaded鈎子(並且您可能還需要其他一些修改)。

附言:我可能會在不久的將來完成並將此代碼發布到Github上。

register_post_type函數的$args查找類似的內容->

taxonomies => array('categories');

去掉它

為您的自定義帖子類型使用功能注冊分類法

注冊分類法

像這樣添加分類法。

'taxonomies' => array('timeline','category',),

總代碼對於管理員來說像這樣:

// Admin
            'capability_type' => 'post',
            'menu_icon'     => 'dashicons-businessman',
            'menu_position' => 10,
            'query_var'     => true,
            'show_in_menu'  => true,
            'show_ui'       => true,
            'taxonomies' => array('timeline','category',),
            'supports'      => array(
            'title',
            'editor',
            'custom_fields',
            'timeline',
            ),

編輯wp-includes/taxonomy.php並在其中寫有'custom post name here'地方寫上您的自定義帖子類型名稱:

http://img.prntscr.com/img?url=http://i.imgur.com/wl7VVjT.png

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM