Best Practice to Insert WordPress Category with PHP Code – WordPress Tutorial

By | August 21, 2019

Sometimes, we need insert a wordpress category by php code. In this tutorial, we will introduce you how to insert a wordpress category, there are some questions you shoud notice.

wordpress categories and tags

Two important things in wordpress category

First one is category name, such as python, medical.

Sencode one is category slug, which is the unique feature of category, such as java-programming.

How to insert a wordpress category with php code?

1.Check a wordpress category exists or not

<?php
$cat = 'C++';
$cat_ids = array(); // save category ids
$c_slug = sanitize_title($cat);
$term = term_exists($c_slug, 'category' );
if ( 0 !== $term && null !== $term ) {
    $cat_ids[]=$term['term_id'];
}
?>

Here, we use wordpress term_exists() function to check a wordpress exists or not.

term_exists( int|string $term, string $taxonomy = '', int $parent = null )

Where

$term: (int|string) (Required) The term to check. Accepts term ID, slug, or name.

However, from code above we can notice, as to words c++ programming and c programming, their slugs are the same (c-programming), so we should process this situation.

<?php
$cat = 'C++';
$cat_ids = array(); // save category ids

$c_temp = $cat;
$c_temp = str_replace("#"," sharp ",$c_temp);
$c_temp = str_replace("+"," plus ",$c_temp);

$c_slug = sanitize_title($c_temp);
$term = term_exists($c_slug, 'category' );
if ( 0 !== $term && null !== $term ) {
    $cat_ids[]=$term['term_id'];
}
?>

Then we can insert a new wordpress category.

Insert a new wordpress category

$term = wp_insert_term(
	$cat, // the term 
	'category',
	array('slug'=>$c_slug)
	);
$cat_ids[]=$term['term_id'];

Here we use wordpress wp_insert_term() to insert a new wordpress category.

wp_insert_term( string $term, string $taxonomy, array|string $args = array() )

Then we insert a new category successfully.

Leave a Reply

Your email address will not be published. Required fields are marked *