注册新的公共帖子类型或分类时,请始终刷新重写规则。否则,当URL映射到查询时,内部重写规则将不会考虑到这一点。
您可以通过钩住registered_post_type
和来自动执行该过程registered_taxonomy
。
以下是根据评论和其他人的反馈更新的代码。
在GitHub上以插件T5 Silent Flush下载。
add_action( 'registered_post_type', 't5_silent_flush_cpt', 10, 2 );
add_action( 'registered_taxonomy', 't5_silent_flush_tax', 10, 3 );
/**
* Flush rules for custom post types.
*
* @wp-hook registered_post_type
* @param string $post_type
* @param stdClass $args
* @return void
*/
function t5_silent_flush_cpt( $post_type, $args )
{
if ( $args->_builtin )
return;
if ( ! $args->public )
return;
if ( ! $args->publicly_queryable )
return;
if ( ! $args->rewrite )
return;
$slug = $post_type;
if ( isset ( $args->rewrite['slug'] ) && is_string( $args->rewrite['slug'] ) )
$slug = $args->rewrite['slug'];
$rules = get_option( 'rewrite_rules' );
if ( ! isset ( $rules[ $slug . '/?$'] ) )
flush_rewrite_rules( FALSE );
}
/**
* Flush rules for custom post taxonomies.
*
* @wp-hook registered_taxonomy
* @param string $taxonomy
* @param string $object_type
* @param array $args
* @return void
*/
function t5_silent_flush_tax( $taxonomy, $object_type, $args )
{
// No idea why we get an array here, but an object for post types.
// Objects are easier to write, so ...
$args = (object) $args;
if ( $args->_builtin )
return;
if ( ! $args->public )
return;
if ( ! $args->rewrite )
return;
$slug = $taxonomy;
if ( isset ( $args->rewrite['slug'] ) && is_string( $args->rewrite['slug'] ) )
$slug = $args->rewrite['slug'];
$rules = get_option( 'rewrite_rules' );
if ( ! isset ( $rules[ $slug . '/(.+?)/?$'] ) )
flush_rewrite_rules( FALSE );
}
每当您创建新的帖子类型或分类法时,都会刷新规则。无需再次访问永久链接设置。