本文章要实现的目标见标题所示。 如何实现呢? 我们只需要在当前主题函数文件functions.php当中结尾添加如下代码,并重新保存固定链接即可。 我这里使用的固定链接形式是:/%category%/%post_id%.html 我这里的wordpress版本是:6.7.1 php版本是:7.4 /** * 删除文章和分类链接中的父级分类名 */ function remove_parent_categories_from_links($permalink, $post = null, $leavename = false) { // 处理文章链接 if ($post && is_object($post)) { $categories = get_the_category($post->ID); if (!empty($categories)) { // 按ID排序分类 usort($categories, '_usort_terms_by_ID'); // 获取第一个分类 $category = $categories[0]; // 如果有父级分类 if ($category->parent) { // 获取所有父级分类路径 $parents = get_category_parents($category->parent, false, '/', true); if (!is_wp_error($parents)) { // 移除父级分类路径 $permalink = str_replace($parents, '', $permalink); } } } } return $permalink; } /** * 处理分类链接 */ function remove_parent_categories_from_term_link($termlink, $term) { if ($term->parent && $term->taxonomy === 'category') { // 获取父级分类路径 $parents = get_category_parents($term->parent, false, '/', true); if (!is_wp_error($parents)) { // 移除父级分类路径 $termlink = str_replace($parents, '', $termlink); } } return $termlink; } // 应用到文章链接 add_filter('post_link', 'remove_parent_categories_from_links', 10, 3); add_filter('post_type_link', 'remove_parent_categories_from_links', 10, 3); // 应用到分类链接 add_filter('term_link', 'remove_parent_categories_from_term_link', 10, 2); /** * 修改分类链接结构 */ function modify_category_permastruct() { global $wp_rewrite; // 设置分类链接结构为单层 $wp_rewrite->extra_permastructs['category']['struct'] = '%category%'; } add_action('init', 'modify_category_permastruct'); // 首次添加代码时,取消下面的注释并保存一次固定链接设置 // add_action('init', function() { // global $wp_rewrite; // $wp_rewrite->flush_rules(); // }); 看,是不是很简单?! @_* 未经允许不得转载:泥人传说 » wordpress通过函数去除多层父级分类别名和文章的父级分类别名,实现优化链接及提升搜索引擎抓取的目标。(亲测有效) wordpress优化wordpress分类去除父级分类链接wordpress去除父级链接wordpress固定链接优化wordpress文章去除父级链接 分享到: 赞(1)