register_post_type_args
云策文档标注
概述
register_post_type_args 是一个 WordPress 过滤器钩子,用于在注册文章类型时修改其参数。它允许开发者动态调整 register_post_type() 函数的参数,例如重写规则或模板设置。
关键要点
- 过滤器钩子名称为 register_post_type_args,接受两个参数:$args(文章类型参数数组)和 $post_type(文章类型键名)。
- 可用于修改特定文章类型的注册参数,如 rewrite slug 或 template,通过条件判断 $post_type 实现。
- 存在更具体的过滤器 register_{$post_type}_post_type_args,针对单个文章类型,且执行顺序在 register_post_type_args 之后,可能覆盖前者的修改。
代码示例
add_filter('register_post_type_args', 'movies_to_films', 10, 2);
function movies_to_films($args, $post_type){
if ($post_type == 'movies'){
$args['rewrite']['slug'] = 'films';
}
return $args;
}注意事项
- 使用 register_{$post_type}_post_type_args 时,需注意其执行顺序在 register_post_type_args 之后,可能覆盖前者的更改。
原文内容
Filters the arguments for registering a post type.
Parameters
$argsarray-
Array of arguments for registering a post type.
See the register_post_type() function for accepted arguments.More Arguments from register_post_type( … $args )
Post type registration arguments.
$post_typestring-
Post type key.
Source
$args = apply_filters( 'register_post_type_args', $args, $this->name );
Changelog
| Version | Description |
|---|---|
| 4.4.0 | Introduced. |
Skip to note 3 content
Konrad Chmielewski
Example of Custom Post Type args change via filter hook. Changing rewrite slug from
moviestofilms:add_filter('register_post_type_args', 'movies_to_films', 10, 2); function movies_to_films($args, $post_type){ if ($post_type == 'movies'){ $args['rewrite']['slug'] = 'films'; } return $args; }Skip to note 4 content
mrwweb
You can also use `register_{$post_type}_post_type_args` to target a specific post type.
For example, you can use `register_post_post_type_args` to target only the Post post type and modify how it’s registered:
add_filter( 'register_post_post_type_args', 'wpdocs_default_posts_template' ); /** * Add default template for new Posts with the Featured Image as the first block */ function wpdocs_default_posts_template( $args ) { $args['template'] = array( array( 'core/post-featured-image', array( 'align' => 'center' ) ) ); return $args; }register_{$post_type}_post_type_argsis called after the filterregister_post_type_argsand thus can overwrite possible changes of the first one!