首先,请注意是否值得这样做:
影响 SEO 的因素实际上有数百个。您不需要实施所有这些,而且许多总体上不会产生很大的影响。在我看来,这样做很可能不会产生任何显着的效果,而且只会让事情变得更加困难。
更重要的是,对SEO有影响slug 应包含您的关键字,如果您以编程方式更改它们,则有无法确保 slug 包含关键字,所以你甚至可能弊大于利。
仅供参考,几个版本前,WP 被更改为对 slugs 实施此限制,然后很快又改回来。这对我来说意味着它可能不是很有用或不太实用。
但是,如果您仍然想这样做:
限制新段中的单词
你问题中的代码来自这篇文章,对吗?:如何限制 WordPress 永久链接或 slug 中的字数? https://permalinkmanager.pro/docs/filters-hooks/how-to-limit-the-number-of-words-in-wordpress-permalinks/
您使用的第一个示例是与他们的插件一起使用的。下一个示例(包含在下面)将在没有插件的情况下在 WordPress 中运行。这可以添加到您的functions.php中。
更新:我已将代码合并到自动删除 URL 中的短词 https://www.isitwp.com/better-seo-automatically-remove-short-words-from-url/进入此函数以删除少于 3 个字符的短单词,请参阅下面的更新函数。
<?php
/**
* Trim native slugs
*/
function pm_trim_native_slug($slug, $post_ID, $post_status, $post_type, $post_parent) {
global $wpdb;
$max_words = 5; // Limit the number of words to 5; This value can be changed.
$words = explode('-', $slug);
/* UPDATED CODE TO REMOVE SHORT WORDS */
$min_word_length = 2;
foreach ($words as $k => $word) {
if (strlen($word) <= $min_word_length)
unset($words[$k]);
}
/* END OF UPDATED CODE FOR SHORT WORDS */
if(count($words) > $max_words) {
$slug = implode("-", array_slice($words, 0, $max_words));
// Make the slugs unique
$check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1";
$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $slug, $post_ID));
if($post_name_check) {
$suffix = 2;
do {
$alt_post_name = _truncate_post_slug($slug, 200 - (strlen($suffix) + 1)) . "-$suffix";
$post_name_check = $wpdb->get_var($wpdb->prepare($check_sql, $alt_post_name, $post_type, $post_ID, $post_parent));
$suffix++;
} while ($post_name_check);
$slug = $alt_post_name;
}
}
return $slug;
}
add_filter('wp_unique_post_slug', 'pm_trim_native_slug', 99, 5);
请注意,这仅适用于newslugs,您仍然需要重新生成旧的 slugs,或者编写代码来遍历现有的 slugs 来更新它们。
更新现有的 slugs
您可以将此函数添加到您的functions.php中以获取所有slug,调用上面的函数以生成新的slug,然后在数据库中更新它:
function limit_all_existing_slugs(){
// get all posts
$posts = get_posts( array ( 'numberposts' => -1 ) );
foreach ( $posts as $post ){
// create the new slug using the pm_trim_native_slug function
$new_slug = pm_trim_native_slug($post->post_name,
$post->ID,
$post->post_status,
$post->post_type,
$post->post_parent);
// only do the update if the new slug is different
if ( $post->post_name != $new_slug ){
wp_update_post(
array (
'ID' => $post->ID,
'post_name' => $new_slug
)
);
}
}
}
请注意,上面的代码是我自己的,未经测试,因此请确保先在测试环境中尝试一下。
如何使用此功能
要更新所有现有的 slugs,您只需按需调用此函数一次,而不是自动调用(否则每次加载 function.php 时它都会更新 slugs)。您可以通过创建单独的独立页面,在 WP 外部的外部脚本中执行此操作,如下所示:
<?php
include('wp-load.php'); //Include the wp-load.php file
define('WP_USE_THEMES', false); //We don't need the theme files
echo "<p>About to update all slugs...</p>";
limit_all_existing_slugs();
echo "<p>...DONE</p>";
?>