您可以将以下内容添加为插件或主题functions.php
文件我们需要做的是添加一个重写标记custom query var,最后用相关的post slug替换重写标记。从我的代码到你的代码,有些东西可能会有所不同。我想chapters
是post类型的slug,并且关系字段返回的是ID而不是对象,您可能需要根据设置更改这些内容。
您需要做的一件事是在创建chapters
post类型,您需要在重写段塞上添加占位符:
/**
* Create Rewrite Tag
* We\'ll be able to hook in and replace this placeholder
*
* @return void
*/
function wpse285382_chapters_setup() {
// Add rewrite tag
add_rewrite_tag(
\'%manga%\', // Placeholder
\'([^&]+)\', // Regex
\'manga=\' // Expected query var
);
// Assign rewrite tag in post registation
register_post_type( \'chapters\', array(
/* ... */
\'rewrite\' => array( \'slug\' => \'mangas/%manga%\', \'with_front\' => false ),
/* ... */
) );
}
add_action( \'init\', \'wpse285382_chapters_setup\' );
/**
* Replace the placeholder rewrite tag with expected manga
*
* @param String $post_link
* @param WP_Post $post
*
* @return String $post_link
*/
function wpse285382_chapter_link_replacements( $post_link, $post ) {
// No Post ID? Drop out
if( empty( $post ) ) {
return $post_link;
}
// Make sure our post type is correct
if( empty( $post ) || \'chapters\' !== $post->post_type ) {
return $post_link;
}
// Get related manga field
$manga = get_field( \'related_manga\', $post->ID );
if( ! empty( $manga ) ) {
// Grab Post Slug
$manga_slug = get_post_field( \'post_name\', $manga );
// Replace rewrite tag in the given URL
$post_link = str_replace( \'%manga%\', $manga_slug, $post_link );
}
return $post_link;
}
add_filter( \'post_type_link\', \'wpse285382_chapter_link_replacements\', 9, 2 );
最后一位应该重定向任何不匹配的帖子。我们确保有一个slug可以使用,我们分配了一个相关的post ID,并且给定的slug和相关的post slug是相同的,如果不是,我们将它们重定向回归档页面(或者您需要将它们指向的任何地方)。
/**
* Redirect mismatched related posts
*
* @return void
*/
function wpse285382_chapter_redirects() {
global $post, $wp_query;
if( ! is_singular( \'chapterss\' ) ) {
return;
}
$redirect_to = get_post_type_archive_link( \'chapters\' );
$given_slug = $wp_query->get( \'manga\' );
$expected_manga = get_field( \'related_manga\', $post->ID );
if( empty( $given_slug ) || empty( $expected_manga ) ) {
wp_redirect( $redirect_to );
exit();
}
$expected_slug = get_post_field( \'post_name\', $expected_manga );
if( $given_slug !== $expected_slug ) {
wp_redirect( $redirect_to );
exit();
}
}
add_action( \'template_redirect\', \'wpse285382_chapter_redirects\' );