Присвойте категории определенным публикациям в WordPress

Чтобы создать категорию для определенного поста в WordPress, вы можете использовать несколько методов. Давайте рассмотрим некоторые из них вместе с примерами кода:

Метод 1: использование функции wp_set_object_terms()

// Get the post ID
$post_id = get_the_ID();
// Assign the category slug or ID
$category = 'category-slug'; // or $category = 3;
// Set the category for the post
wp_set_object_terms($post_id, $category, 'category');

Метод 2: использование функции wp_set_post_categories()

// Get the post ID
$post_id = get_the_ID();
// Assign the category slug or ID
$category = 'category-slug'; // or $category = 3;
// Set the category for the post
wp_set_post_categories($post_id, $category);

Метод 3. Использование функции wp_set_post_terms()

// Get the post ID
$post_id = get_the_ID();
// Assign the category slug or ID
$category = 'category-slug'; // or $category = 3;
// Set the category for the post
wp_set_post_terms($post_id, $category, 'category');

Метод 4. Использование функции wp_set_object_terms() с несколькими категориями

// Get the post ID
$post_id = get_the_ID();
// Assign an array of category slugs or IDs
$categories = array('category1', 'category2', 'category3'); // or $categories = array(1, 2, 3);
// Set the categories for the post
wp_set_object_terms($post_id, $categories, 'category');

Метод 5. Использование функции wp_set_post_categories() с несколькими категориями

// Get the post ID
$post_id = get_the_ID();
// Assign an array of category slugs or IDs
$categories = array('category1', 'category2', 'category3'); // or $categories = array(1, 2, 3);
// Set the categories for the post
wp_set_post_categories($post_id, $categories);

Метод 6. Использование функции wp_set_post_terms() с несколькими категориями

// Get the post ID
$post_id = get_the_ID();
// Assign an array of category slugs or IDs
$categories = array('category1', 'category2', 'category3'); // or $categories = array(1, 2, 3);
// Set the categories for the post
wp_set_post_terms($post_id, $categories, 'category');

Это некоторые методы, которые вы можете использовать для присвоения категорий определенным публикациям в WordPress. Выберите метод, который соответствует вашим потребностям, и реализуйте его в своем проекте разработки WordPress.