wp_check_for_changed_slugs

函式
wp_check_for_changed_slugs ( $post_id, $post, $post_before )
引數
  • (int) $post_id Post ID.
    Required:
  • (WP_Post) $post The post object.
    Required:
  • (WP_Post) $post_before The previous post object.
    Required:
定義位置
相關方法
wp_check_for_changed_dateswp_check_locked_postswp_cache_get_last_changedwp_check_filetype_and_extcheck_import_new_users
引入
2.1.0
棄用
-

wp_check_for_changed_slugs: 這是一個檢查文章或頁面中已更改的片語的函式。如果有任何變化,它可以用來更新文章或頁面的slug。

檢查已釋出的文章物件是否有改變的標題,並儲存舊的標題。

當任何型別的文章物件被更新時,通過比較當前和之前的文章物件,該函式被使用。

如果slug被改變了,並且還沒有成為舊slug的一部分,那麼它將被新增到文章的元欄位(’_wp_old_slug’),用於儲存該文章的舊slug。

這個函式最合理的用法是重定向已更改的文章物件,這樣,那些連結到已更改的文章的物件將被重定向到新的文章。

function wp_check_for_changed_slugs( $post_id, $post, $post_before ) {
	// Don't bother if it hasn't changed.
	if ( $post->post_name == $post_before->post_name ) {
		return;
	}

	// We're only concerned with published, non-hierarchical objects.
	if ( ! ( 'publish' === $post->post_status || ( 'attachment' === get_post_type( $post ) && 'inherit' === $post->post_status ) ) || is_post_type_hierarchical( $post->post_type ) ) {
		return;
	}

	$old_slugs = (array) get_post_meta( $post_id, '_wp_old_slug' );

	// If we haven't added this old slug before, add it now.
	if ( ! empty( $post_before->post_name ) && ! in_array( $post_before->post_name, $old_slugs, true ) ) {
		add_post_meta( $post_id, '_wp_old_slug', $post_before->post_name );
	}

	// If the new slug was used previously, delete it from the list.
	if ( in_array( $post->post_name, $old_slugs, true ) ) {
		delete_post_meta( $post_id, '_wp_old_slug', $post->post_name );
	}
}

常見問題

FAQs
檢視更多 >