在Wordpress 3.0的自定义post_类型永久链接中使用日期
我正在向Wordpress添加一个自定义post_类型,并希望permalink结构如下所示:在Wordpress 3.0的自定义post_类型永久链接中使用日期,wordpress,date,permalinks,custom-post-type,Wordpress,Date,Permalinks,Custom Post Type,我正在向Wordpress添加一个自定义post_类型,并希望permalink结构如下所示: /%post_type%/%year%/%monthnum%/%postname%/ 我不知道如何添加日期标签。使用此代码,为我提供/my\u type/example post slug/: register_post_type( 'customtype', array( ...other options... 'rewrite' => array('slug' =>
/%post_type%/%year%/%monthnum%/%postname%/
我不知道如何添加日期标签。使用此代码,为我提供/my\u type/example post slug/
:
register_post_type( 'customtype', array(
...other options...
'rewrite' => array('slug' => 'my_type'),
));
如何包括日期?使用此选项,它100%有效:
'rewrite' => array('slug'=>date('Y').'/'.date('m').'/custom_post_type_slug','with_front'=>true)
您可以通过插件实现这一点。只需安装插件并在设置中更改永久链接格式。我找到了一个部分解决方案,允许在地址栏中加载页面时识别和保留永久链接,但不在编辑屏幕或网站上帖子的其他链接中更新。 将以下内容添加到functions.php或特定于站点的插件中,用帖子类型的标识符替换示例帖子类型
function example_rewrite() {
add_rewrite_rule('^example-post-type/([0-9]{4})/([0-9]{1,2})/([^/]*)/?','index.php?post_type=example-post-type&year=$matches[1]&monthnum=$matches[2]&name=$matches[3]','top');
}
add_action('init', 'example_rewrite');
这使用了文档中的重写API
如需了解了解该流程的更多提示,请参阅
要记住的一件事是,无论你怎么做,两个帖子都不可能有相同的slug,即使它们有不同的日期。这是因为,如果永久链接方案发生更改,它们可能会发生冲突并导致错误。您需要将WordPress结构标记添加到
重写
属性中,如下所示:
register_post_type('customtype',array(
....
'rewrite' => array('slug' => 'customtype/%year%/%monthnum%','with_front' => false)
));
然后添加一个post\u type\u链接
过滤器,为自定义帖子重写URL中的结构标记,以便标记工作:
function custompost_post_type_link($url, $post) {
if ( 'customtype' == get_post_type($post) ) {
$url = str_replace( "%year%", get_the_date('Y'), $url );
$url = str_replace( "%monthnum%", get_the_date('m'), $url );
}
return $url;
}
add_filter('post_type_link', 'custompost_post_type_link', 10, 2);
关于创建这样的自定义帖子,您可以参考本文了解copypasta代码(封装在类中)。本文还有一些额外的解释和一些附加功能:
编辑:顺便说一句,您还需要在完成后进行编辑,这样才能正常工作