我有两种自定义帖子类型Location
和House
。
我正在尝试将房屋信息类型的网址重写为/location/%LocationName%/house
我用add_filter('post_type_link', 'postTypeLink', 13, 3)
替换了%LocationName%
,并且永久链接确实更改为我想要的格式,但是,当我单击链接时,它只会抛出一个页面找不到错误。
我已经打印了wp_query
,发现wp仍在尝试进行Location
查询,但是名称为%LocationName%/house
例如众议院有一个帖子yellow
。因此,URL domain.com/location/london/house/yellow将进行名称为/london/house/yellow
的位置查询,而不是名称为yellow
的房屋查询。导致找不到页面,因为该位置没有任何此类帖子。
我尝试使用add_rewrite_rule
或保存永久链接,但这只会导致相同的结果。
代码在下面。
add_action( 'init', 'rewrite_tag', 10, 0 );
function rewrite_tag() {
add_rewrite_tag( '%locationName%', '([^/]*)/?$', 'locationName=' );
add_rewrite_rule(
'^location/([^/]*)/?$/house',
'index.php?post_type=house&locationName=$matches[1]',
'top');
flush_rewrite_rules(false);
}
$args = array(
'labels' => $labels,
'description' => 'Manage Research Publication',
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => array(
'slug' => 'location/%locationName%/house',
'with_front'=> false,
'hierarchical' => true
),
'has_archive' => false,
'hierarchical' => true,
'menu_icon' => 'dashicons-clipboard',
'menu_position' => null,
'supports' => array('title', 'editor', 'thumbnail'),
'show_in_rest' => true,
'rest_base' => 'house',
'taxonomies' => array('category'),
'rest_controller_class' => 'WP_REST_Posts_Controller',
);
register_post_type( 'house', $args );
add_filter('post_type_link', 'postTypeLink', 13, 3);
function postTypeLink($link, $post) {
global $post;
if (get_post_type($post) === 'location') {
$location = a variable from global post
$link = str_replace('%LocationLName%', $location, $link);
}
return $link;
}