函数文档

wp_set_unique_slug_on_create_template_part()

💡 云策文档标注

概述

此函数用于在创建自动草稿模板部件时设置自定义 slug,确保唯一性并关联主题分类。仅适用于常规 WordPress 编辑器创建的自动草稿。

关键要点

  • 函数 wp_set_unique_slug_on_create_template_part 在自动草稿模板部件创建时自动设置唯一 slug。
  • 仅处理 post_status 为 'auto-draft' 的帖子,否则直接返回。
  • 如果帖子没有 post_name,则使用 'custom_slug_' 加 uniqid() 生成唯一 slug 并更新帖子。
  • 检查帖子是否关联 'wp_theme' 分类,若无则使用 get_stylesheet() 设置当前主题为分类项。

代码示例

function wp_set_unique_slug_on_create_template_part( $post_id ) {
	$post = get_post( $post_id );
	if ( 'auto-draft' !== $post->post_status ) {
		return;
	}

	if ( ! $post->post_name ) {
		wp_update_post(
			array(
				'ID'        => $post_id,
				'post_name' => 'custom_slug_' . uniqid(),
			)
		);
	}

	$terms = get_the_terms( $post_id, 'wp_theme' );
	if ( ! is_array( $terms ) || ! count( $terms ) ) {
		wp_set_post_terms( $post_id, get_stylesheet(), 'wp_theme' );
	}
}

注意事项

  • 此函数仅对常规 WordPress 编辑器创建的自动草稿模板部件有效,如果页面被移除则不再需要。
  • 参数 $post_id 为必填整数,表示帖子 ID。
  • 函数在 WordPress 5.9.0 版本中引入。

📄 原文内容

Sets a custom slug when creating auto-draft template parts.

Description

This is only needed for auto-drafts created by the regular WP editor.
If this page is to be removed, this will not be necessary.

Parameters

$post_idintrequired
Post ID.

Source

function wp_set_unique_slug_on_create_template_part( $post_id ) {
	$post = get_post( $post_id );
	if ( 'auto-draft' !== $post->post_status ) {
		return;
	}

	if ( ! $post->post_name ) {
		wp_update_post(
			array(
				'ID'        => $post_id,
				'post_name' => 'custom_slug_' . uniqid(),
			)
		);
	}

	$terms = get_the_terms( $post_id, 'wp_theme' );
	if ( ! is_array( $terms ) || ! count( $terms ) ) {
		wp_set_post_terms( $post_id, get_stylesheet(), 'wp_theme' );
	}
}

Changelog

Version Description
5.9.0 Introduced.