我当前使用Post name
对于permalink结构。我想从永久链接末尾的字段中添加文本。当Post
是否已发布?
在我的情况下,我使用Advanced Custom Fields
每个帖子都有标题和副标题。目前,permalink是/title/
但我想成为/title-subtitle/
.
Edit: 与此类似previous question, 除了我只想在帖子创建时这样做,而不是在以后的帖子版本上,因为这会修改帖子的URL,这对SEO来说是一场灾难。
我当前使用Post name
对于permalink结构。我想从永久链接末尾的字段中添加文本。当Post
是否已发布?
在我的情况下,我使用Advanced Custom Fields
每个帖子都有标题和副标题。目前,permalink是/title/
但我想成为/title-subtitle/
.
Edit: 与此类似previous question, 除了我只想在帖子创建时这样做,而不是在以后的帖子版本上,因为这会修改帖子的URL,这对SEO来说是一场灾难。
以下是我为实现这一点所做的:
function slug_save_post_callback( $post_ID, $post, $update ) {
// allow \'publish\', \'draft\', \'future\'
if ($post->post_type != \'post\' || $post->post_status == \'auto-draft\')
return;
// only change slug when the post is created (both dates are equal)
if ($post->post_date_gmt != $post->post_modified_gmt)
return;
// use title, since $post->post_name might have unique numbers added
$new_slug = sanitize_title( $post->post_title, $post_ID );
$subtitle = sanitize_title( get_field( \'subtitle\', $post_ID ), \'\' );
if (empty( $subtitle ) || strpos( $new_slug, $subtitle ) !== false)
return; // No subtitle or already in slug
$new_slug .= \'-\' . $subtitle;
if ($new_slug == $post->post_name)
return; // already set
// unhook this function to prevent infinite looping
remove_action( \'save_post\', \'slug_save_post_callback\', 10, 3 );
// update the post slug (WP handles unique post slug)
wp_update_post( array(
\'ID\' => $post_ID,
\'post_name\' => $new_slug
));
// re-hook this function
add_action( \'save_post\', \'slug_save_post_callback\', 10, 3 );
}
add_action( \'save_post\', \'slug_save_post_callback\', 10, 3 );
它生成并更新slug
. 之前由WP生成的slug不能重用,因为如果标题/slug已经在另一篇文章中使用,那么它可以具有唯一的编号。所以,我清理了标题。然后wp_update_post
确保新的slug没有重复项wp_unique_post_slug
.我能找到的唯一方法是在发布时进行此操作,即比较创建时间和修改时间。只有在创建帖子时,它们才相等。这个$update
参数无效,因为true
用于发布。
在您的功能中。php文件,您应该能够通过以下方式实现所需的功能:
function adjust_permalinks() {
global $wp_rewrite;
$title = get_field( \'title_field\' );
$subtitle = get_field( \'sub_title_field\' );
$wp_rewrite->set_permalink_structure( $title . \'-\' . $subtitle );
$wp_rewrite->flush_rules();
}
add_action(\'init\', \'adjust_permalinks\');
这会将您的永久链接结构设置为始终使用$标题(&A)$字幕我在我的网站上使用网页和博客帖子。页面获取URL示例。org/%postname%/,并基于Permalink设置,posts获取URL示例。组织/博客/%postname%/。完美的我有一个自定义的帖子类型,由我网站上的另一个组用于他们的网页。在注册post类型时,我为它们提供了一个重写slug:\'rewrite\' => array(\'slug\' => \'ncfpw\'),然而,他们的页面得到了URL示例。组织/博客/ncfpw/%博文名%/我怎样才能摆脱;博客;在他们的URL中?