3

我已经阅读了我能找到的每一篇博文,但似乎没有什么对我有用。我需要做的就是让 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 );
4

4 回答 4

5

我刚刚发现这个老问题没有正确和完整的答案。所以我把这篇文章写给对这个话题感兴趣的人。

我会详细解释:

如何注册 CPT 和自定义分类并添加默认术语(不可删除)

以及当没有通过 CPT 元框选择其他术语时,如何将此默认术语注册到我们的自定义帖子类型。

继续的步骤:

  1. 您需要register_post_type在初始化后使用函数注册您的 CPT。
  2. register_taxonomy注册CPT 后使用功能后注册自定义分类。
  3. 注册后将术语添加到您的自定义分类。
  4. 为您的分类设置默认术语。
  5. 在保存后将默认术语添加到 CPT。

注意:我已更改问题中提供的代码结构并使用单例方法并删除了特定于该问题的部分(例如重写规则等)。我还将 CPT 名称更改为photo,分类名称更改为 ,gallery_cat并将默认术语 slug 更改为default_gallery_cat

重要提示: default_{$taxonomy}选项用于将默认类别设置为不可移除,如默认uncategorizedWP 类别

注意:您只能指定一个术语作为默认分类术语。

我已经在代码中将其他细节写成注释。它是一个功能性的 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}钩子用于在保存photoCPT 时添加默认类别术语。

请注意,我使用init hook 来注册东西,但如果您在多站点 WP 安装上,您可以考虑使用 wp_loaded hook 代替(并且您可能还需要一些其他修改)。

PS 我可能会在不久的将来完成并在 Github 上发布此代码。

于 2019-06-13T23:45:08.970 回答
0

register_post_type 在你的函数中寻找类似的东西$args-->

taxonomies => array('categories');

去掉它

为您的自定义帖子类型使用功能注册分类法

注册分类

于 2013-10-31T13:20:57.923 回答
0

添加这样的分类法..

'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',
            ),
于 2014-09-04T15:26:31.210 回答
-1

编辑wp-includes/taxonomy.php并写下您的自定义帖子类型名称'custom post name here'

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

于 2014-03-25T13:50:38.267 回答