問題描述

有很多情況下,主題或插件註冊一個帖子類型,並且您想要修改它。當然有 add_post_type_support()remove_post_type_support(),但是這些不能訪問 register_post_type()所有參數的完整列表。特別是,也許我想要禁用帖子類型存檔,隱藏管理 UI,隱藏搜索等,而只剩下其餘的帖子類型設置。

register_post_type()的 Codex 頁面在我面前搖擺:

Description

Create or modify a post type.

但是在過去,當我嘗試這樣做時,似乎沒有起作用。這個功能是否真的用於修改帖子類型,如果是這樣,你可以簡單地重新聲明幾個參數,並將其餘單獨留下嗎?

看到甚至沒有 deregister_post_type()功能,我不明白如何做到這一點。

最佳解決方案

Is this function really for modifying post types

是。

and if so, can you simply redeclare a couple arguments and leave the rest alone?

否。如果要將參數修改為帖子類型,則需要使用 get_post_type_object 獲取帖子類型對象,修改所需內容,然後使用修改後的類型重新註冊為新的 $ args 參數。

次佳解決方案

經過一番研究,我發現這些答案都不是最新的。

截至 2015 年 12 月 8 日,WordPress 包含一個新的過濾器 register_post_type_args,可以讓您掛接註冊的帖子類型的參數。

function wp1482371_custom_post_type_args( $args, $post_type ) {
    if ( $post_type == "animal-species" ) {
        $args['rewrite'] = array(
            'slug' => 'animal'
        );
    }

    return $args;
}
add_filter( 'register_post_type_args', 'wp1482371_custom_post_type_args', 20, 2 );

第三種解決方案

以下是使用'registered_post_type'篩選器修改另一個插件中的帖子類型的示例。

我使用的插件在它的定義中沒有包含一個 menu_icon,所以我想添加一個我自己的。

<?php
/**
 * Add a menu icon to the WP-VeriteCo Timeline CPT
 *
 * The timeline plugin doesn't have a menu icon, so we hook into 'registered_post_type'
 * and add our own.
 *
 * @param  string $post_type the name of the post type
 * @param  object $args the post type args
 */
function wpse_65075_modify_timeline_menu_icon( $post_type, $args ) {
    // Make sure we're only editing the post type we want
    if ( 'timeline' != $post_type )
        return;

    // Set menu icon
    $args->menu_icon = get_stylesheet_directory_uri() . '/img/admin/menu-timeline.png';

    // Modify post type object
    global $wp_post_types;
    $wp_post_types[$post_type] = $args;
}
add_action( 'registered_post_type', 'wpse_65075_modify_timeline_menu_icon', 10, 2 );

第四種方案

掛鈎到'registered_post_type'後,其他代碼已註冊。它在 register_post_type()的末尾被調用。你有兩個參數:$post_type$args 。現在,您可以更改此帖子類型的任何內容。檢查 $GLOBALS['wp_post_types']有些選項。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。