問題描述
有很多情況下,主題或外掛註冊一個帖子型別,並且您想要修改它。當然有 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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。