好的,我找到了一个解决方案。如果这样做会给我带来麻烦,请告诉我。
基本上,我们以编程方式将类别添加到url链接。
在页面请求中,我们检查url是否以类别/子类别名称开头。如果是这样的话,我们只为这个请求预先准备permalink结构的%category%部分。
好东西是那个网站。com/%类别%/我的文章名称和网站。com/我的文章名称将指向相同的内容。该类别将在第一位,但通过一些调整,你可以把它放在你想要的地方。
设置无类别的permalinks结构(例如,/%年%/%月%/%postname%)将以下内容添加到functions.php
function add_categories( $permalink, $post, $leavename ) {
if( $post->post_type != \'post\' ) return $permalink;
$cats = get_the_category($post->ID);
if( ! count($cats) ) return $permalink;
usort($cats, \'_usort_terms_by_ID\');
$category_object = apply_filters( \'post_link_category\', $cats[0], $cats, $post );
$category_object = get_term( $category_object, \'category\' );
return _clear_uncategorized($category_object, $permalink);
}
function _clear_uncategorized($cat, $permalink) {
if( $cat->slug != \'uncategorized\' ) {
return \'/%category%\' . $permalink;
}
$parent = $cat->parent;
if ( !$parent )
return $permalink;
return _clear_uncategorized($parent, $permalink);
}
add_filter( \'pre_post_link\', \'add_categories\', 9, 3 );
function custom_rewrite_basic() {
global $wp_rewrite;
$categories = get_the_categories();
foreach ($categories as $cat) {
if(strrpos($_SERVER["REQUEST_URI"], $cat) === 0 )
{
$wp_rewrite->permalink_structure = "/%category%" . $wp_rewrite->permalink_structure;
}
}
$wp_rewrite->flush_rules();
}
add_action(\'init\', \'custom_rewrite_basic\');
function get_the_categories( $parent = 0, $pSlug = "" )
{
$slug = array();
$categories = get_categories( "hide_empty=0&parent=$parent" );
if (!$categories) return $slug;
foreach ( $categories as $cat )
{
$slug[] = (($pSlug)?"/".$pSlug : "")."/".$cat->slug;
$slug = array_merge($slug, get_the_categories( $cat->term_id, $cat->slug ));
}
return $slug;
}