How to set category correctly for a custom post created by a remote API call?
- I'm using a plugin - cleverness-to-do-list (https://wordpress.org/plugins/cleverness-to-do-list/#description ).
- I'm aware that the plugin is closed, but I've updated it at my end and gotten it working with my self-hosted Wordpress edition (version 6).
- I'm trying to create a setup where a remote server calls a webpage on my server and POSTs some data.
- That custom PHP webpage is configured to create a new ToDo item (which is placed in the posts table). It does that fine except for setting the category correctly.
Apologies - am new to Wordpress development, so might be missing something obvious here... How can I create a post and set the category correctly?
The relevant portions of the code: `
define( 'WP_USE_THEMES', false );
require_once( $_SERVER[ 'DOCUMENT_ROOT' ] . '/wp-load.php' );
require_once( $_SERVER[ 'DOCUMENT_ROOT' ] . '/wp-admin/includes/post.php' );
...
...
$a2zq3_cat_name = 'Category-name';
$a2zq3_cat_id = get_cat_ID($a2zq3_cat_name);
$a2zq3_category = get_category_by_slug( $a2zq3_cat_name ); // tried the solution proposed at: https://wordpress.stackexchange.com/a/47423/93042
$a2z3_entry_post = array(
'post_type' = 'todo',
'post_title' = $a2z3_entry_POSTTITLE,
'post_content' = $a2z3_entry_POSTCONTENT,
'post_status' = 'publish',
'post_author' = 1, // the admin is the author
'comment_status' = 'closed',
'ping_status' = 'closed',
'post_category' = array( $a2zq3_category-term_id )
);
// this works
$a2z3_entry_post_id = wp_insert_post( $a2z3_entry_post, true, false );
// these work as well
add_post_meta( $a2z3_entry_post_id, '_status', 0, true );
add_post_meta( $a2z3_entry_post_id, '_priority', 1, true );
add_post_meta( $a2z3_entry_post_id, '_assign', -1, true );
add_post_meta( $a2z3_entry_post_id, '_deadline', '', true );
add_post_meta( $a2z3_entry_post_id, '_progress', 0, true );
// these did NOT work, a2zq3_cat_id is the category id (number), a2zq3_cat_name is the category name (string). Both are defined correctly.
wp_set_object_terms( $a2z3_entry_post_id, $a2zq3_cat_id, 'todocategories');
wp_set_object_terms( $a2z3_entry_post_id, $a2zq3_cat_id, $a2zq3_cat_name);
wp_set_object_terms( $a2z3_entry_post_id, $a2zq3_cat_id, 0);
wp_update_term( $a2zq3_cat_id, 'todocategories', array( 'name' = $a2zq3_cat_name ) );
do_action( 'add_term_relationship', $a2z3_entry_post_id, $a2zq3_cat_id, 0);`
Topic categories api plugins custom-post-types Wordpress
Category Web