Skip to main content
6 of 6
Code in backticks
Pieter Goosen
  • 55.4k
  • 23
  • 115
  • 209

Create new custom post and post category of same name

I have a custom post type "Product" and want to create a post category "A Product Name" automatically on creation of a new Product so that the post category (not custom post category) would have the same name as the new Product and so that all relevant posts could be linked to the custom post type.

I was trying to hook into the wp_publish_post but apparently it has been renamed to {$new_status}_{$post->post_type} so I imagine the tag would be publish_product?

    // adds category with name of product automatically
add_filter( 'publish_product', 'my_publish_product' );

function my_publish_product( $post ) {
    global $wpdb;
    $post_type = 'product'; 

    if ( ! $post = get_post( $post ) )
        return;

    if ( 'publish' == $post->post_status )
        return;

    $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) );

    clean_post_cache( $post->ID );

    $old_status = $post->post_status;
    $post->post_status = 'publish';
    wp_transition_post_status( 'publish', $old_status, $post );

    /** This action is documented in wp-includes/post.php */
    do_action( 'edit_post', $post->ID, $post );
    /** This action is documented in wp-includes/post.php */
    do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
    /** This action is documented in wp-includes/post.php */
    do_action( 'save_post', $post->ID, $post, true );
    /** This action is documented in wp-includes/post.php */
    do_action( 'wp_insert_post', $post->ID, $post, true );

    if ( 'post' != $post_type ) {
        return;
    } else {
        add_action( 'wp_insert_post', 'my_wp_insert_post($post->post_name)' );
        return;
    }
}
function my_wp_insert_post( $post_name )
{
    $my_cat = array(
  'cat_ID' => 0,
  'cat_name' => $post_name, 
  'category_parent' => 'products',
  'taxonomy' => 'category' 
  );

    wp_insert_category($my_cat);
}

I'm not terribly adept at using hooks and filters so apologies if this is all wrong or makes no sense.

mantis
  • 790
  • 2
  • 18
  • 38