Add wordpress post to categories using php code by examples

To add a post to wordpress categories by php programming, you can do like this:

Step 1. Load the WordPress environment

<?php
$inc = "E:\\xampp\\htdocs\\www.programmingbyexamples.com\\wp-load.php";
require_once($wordpress_inc_path);
?>

Step 2. Add a post to wordpress categories

Before adding, you must be sure that these categories exist and know their category id, if these categories do not exist, you will can not bind them.

<?php
$post_id=1;
$post_cats=array(8,9);
$result = wp_set_post_terms( $post_id, $terms = $post_cats, $taxonomy = 'category', $append = false );
print_r($result);
?>

Code above add post,which id = 1, to categories, their id = 8 and 9

Leave a Reply

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