所以我使用CPTPermalink Manager 将uri从%postname%更改为%post\\u id%。现在,我需要还原这个过程,我正在寻找一个可以重定向所有帖子的函数:
http://domain.com/cpt1/%post_id%
至http://domain.com/cpt1/%postname%/
感谢您的帮助。所以我使用CPTPermalink Manager 将uri从%postname%更改为%post\\u id%。现在,我需要还原这个过程,我正在寻找一个可以重定向所有帖子的函数:
http://domain.com/cpt1/%post_id%
至http://domain.com/cpt1/%postname%/
感谢您的帮助。如果我理解正确,您首先需要将用户重定向到http://domain.com/cpt1/%postname%/ 之后,您需要重写URL以获得正确的帖子并避免404错误。
所以你来了:
add_action( \'template_redirect\', \'redirect_postid_to_postname\' );
function redirect_postid_to_postname() {
$uri = $_SERVER[\'REQUEST_URI\'];
// Checks if the URI matches what we want. This means the URL should be sth like http://example.com/cpt1/POST_ID
if ( !preg_match( "/^\\/cpt1\\/(\\d+)/", $uri, $matches ) ) {
return;
}
$post_id = $matches[1];
// Checks if $post_id is actually an existent post ID.
$post_obj = get_post( $post_id );
// Checks if a post object was retrieved for the given post ID.
if ( !$post_obj ) {
return;
}
$post_name = $post_obj->post_name; // Keeps post slug.
$site_url = get_site_url(); // Keeps site URL (it\'s supposed to be retrieved without trailing slash).
$location = $site_url . "/cpt1/$post_name"; // Builds the new URL to redirect the user to.
// Redirects!
wp_redirect( $location, 302 );
exit;
}
add_action( \'init\', \'rewrite_custom_postname\', 100 );
function rewrite_custom_postname() {
$uri = $_SERVER[\'REQUEST_URI\'];
// Checks if the URI matches what we want. This means the URL should be sth like http://example.com/cpt1/POST_NAME
if ( !preg_match( "/^\\/cpt1\\/(.+)/", $uri, $matches ) ) {
return;
}
$post_name = $matches[1];
$query_args = array(
\'name\' => $post_name,
\'post_type\' => \'cpt1\',
\'post_status\' => \'publish\',
\'numberposts\' => 1
);
$post_obj = get_posts( $query_args );
// Checks if a post object was retrieved for the given query arguments.
if ( !$post_obj ) {
return;
}
$post_id = $post_obj[0]->ID;
$regex = "^cpt1/{$matches[1]}";
$query = "index.php?p=$post_id";
$after = "top";
add_rewrite_rule( $regex, $query, $after );
}
IMPORTANT!我有自定义帖子,我创建了一个显示所有自定义帖子的页面。示例:www.example.com/archive-page我想知道是否可以更改与此自定义帖子相关的类别和标签的永久链接。现在我有:www.example.com/my-custom-post-type-cats/my-category-1www.example.com/my-custom-post-type-tags/my-tag-1</我想要这样的东西:www.example.com/archive-page?category=1www.e