WordPress函数category_exists检查类别是否存在

WordPress函数category_exists()检查类别是否存在

WordPress函数category_exists()检查类别是否存在

  WordPress 中的函数category_exists()检查类别是否存在。该函数返回一个字符串或 null。如果类别存在,则该函数以字符串形式返回类别的 ID。如果该类别不存在,则该函数返回 null。

  推荐:[最新版]WordPress问答插件免费下载DW Question Answer Pro插件

category_exists()函数基本语法

描述

  检查类别是否存在

用法

$category_exists = category_exists('My Category', 1);

参数

  • $cat_name (int|string) (必需) – 要检查的类别的名称。
  • $category_parent (int) (可选) – 父类别的 ID。默认为空

  推荐:[最新版]Kadence Theme Pro插件下载多用途轻量级WordPress主题

category_exists()函数

  WordPress 中的category_exists()函数用于检查数据库中是否存在类别。(源文件可参考这里

function category_exists( $cat_name, $category_parent = null ) {
	$id = term_exists( $cat_name, 'category', $category_parent );
	if ( is_array( $id ) ) {
		$id = $id['term_id'];
	}
	return $id;
}

  推荐:NEX-Forms插件下载WordPress表单生成器插件+ Addons

如何使用category_exists()

  检查类别是否存在,此示例检查类别“旅行”是否存在。

$category_exists = category_exists('Travel');
if ($category_exists) {
    echo "The category exists";
} else {
    echo "The category does not exist";
}

  检查子类别是否存在,此示例检查“旅行”父类别下是否存在“亚洲”类别。

$parent_id = get_cat_ID('Travel');
$category_exists = category_exists('Asia', $parent_id);
if ($category_exists) {
    echo "The sub-category exists";
} else {
    echo "The sub-category does not exist";
}

  如果类别不存在则创建,此示例将创建一个新类别“摄影”(如果尚不存在)。

if (!category_exists('Photography')) {
    wp_create_category('Photography');
}

  检查多个类别,此示例检查多个类别是否存在。

$categories = array('Travel', 'Food', 'Photography');
foreach ($categories as $category) {
    if (category_exists($category)) {
        echo "The category $category exists";
    } else {
        echo "The category $category does not exist";
    }
}

  创建多个类别(如果不存在),此示例将创建多个类别(如果它们不存在)。

$categories = array('Travel', 'Food', 'Photography');
foreach ($categories as $category) {
    if (!category_exists($category)) {
        wp_create_category($category);
    }
}

  推荐:7个WooCommerce变体样本插件

  推荐:WordPress函数使用手册

5/5 - (1 vote)

晓得博客,版权所有丨如未注明,均为原创
晓得博客 » WordPress函数category_exists()检查类别是否存在

转载请保留链接:https://www.pythonthree.com/wordpress-category-exists/

Claude、Netflix、Midjourney、ChatGPT Plus、PS、Disney、Youtube、Office 365、多邻国Plus账号购买,ChatGPT API购买,优惠码XDBK,用户购买的时候输入优惠码可以打95折

Chatgpt-Plus注册购买共享账号
滚动至顶部