我会创建一个自定义帖子类型“商店”,然后创建一个自定义分类。
然后为每个国家/地区添加新的自定义分类并将其分配给自定义帖子类型“商店”。
在functions.php中注册您的自定义帖子类型,如下所示:
add_action( 'init', 'custom_post_types', 0 );
function custom_post_types() {
//shops
register_post_type( 'shops',
array(
'labels' => array(
'name' => __( 'Shops' ),
'singular_name' => __( 'Shops' ),
'all_items' => __( 'All Shops'),
),
'capabilities' => array(
'edit_post' => 'update_core',
'read_post' => 'update_core',
'delete_post' => 'update_core',
'edit_posts' => 'update_core',
'edit_others_posts' => 'update_core',
'delete_posts' => 'update_core',
'publish_posts' => 'update_core',
'read_private_posts' => 'update_core'
),
'taxonomies' => array('countries'),
'menu_position' => 5,
'public' => true,
'has_archive' => false,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt' ),
"rewrite" => array(
"slug"=>'news/%countries%',
"with_front" => false
),
)
);
}
然后注册您的自定义分类:
add_action( 'init', 'build_taxonomies', 0 );
function build_taxonomies() {
register_taxonomy('countries', 'shops', array('hierarchical' => true, 'label' => 'Countries', 'query_var' => true, 'rewrite' => array( 'slug' => 'shops', 'with_front' => false)));
}
为了在注册自定义帖子类型时在重写规则中使用 %countries%/,您需要告诉 WordPress 这意味着什么。你这样做:
add_filter( 'post_type_link', 'wpa_shops_permalinks', 1, 2 );
function wpa_shops_permalinks( $post_link, $post ){
if ( is_object( $post ) && $post->post_type == 'shops' ){
$terms = wp_get_object_terms( $post->ID, 'countries' );
if( $terms ){
return str_replace( '%countries%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}