WordPress.org

Ready to get started?Download WordPress

Forums

Automatically add Custom Post Type to specific category (12 posts)

  1. ramco
    Member
    Posted 1 year ago #

    Hi!

    I spent the last two days on that topic and I really can't figure out how to do it.

    I created a CPT called "Products". Now I want each post to be sorted in the Category named after the singular name of that CPT, here: Products.
    Furthermore, if there is no such category it shall be created first (based on the singular name for more flexibility).

    This is what I have (after tons of revisiosn and experimentation):

    // let's create the function for the (custom) product type
    function product_post() {
    	// creating (registering) the (custom) product type
    	register_post_type( 'product', /* (http://codex.wordpress.org/Function_Reference/register_post_type) */
    	 	// let's now add all the options for this post type
    		array('labels' => array(
    			'name' => __('Albums & Merch', 'bonestheme'), /* This is the Title of the Group */
    			'singular_name' => __('Product', 'bonestheme'), /* This is the individual type */
    			'all_items' => __('All Products', 'bonestheme'), /* the all items menu item */
    			'add_new' => __('Add New Product', 'bonestheme'), /* The add new menu item */
    			'add_new_item' => __('Add New Product', 'bonestheme'), /* Add New Display Title */
    			'edit' => __( 'Edit', 'bonestheme' ), /* Edit Dialog */
    			'edit_item' => __('Edit Product', 'bonestheme'), /* Edit Display Title */
    			'new_item' => __('New Product', 'bonestheme'), /* New Display Title */
    			'view_item' => __('View Product', 'bonestheme'), /* View Display Title */
    			'search_items' => __('Search Product', 'bonestheme'), /* Search Custom Type Title */
    			'not_found' =>  __('Nothing found in the Database. Frakin\' nutting, man. No Products AT ALL.', 'bonestheme'), /* This displays if there are no entries yet */
    			'not_found_in_trash' => __('Nothing found in Trash but a cockroach', 'bonestheme'), /* This displays if there is nothing in the trash */
    			'parent_item_colon' => ''
    			), /* end of arrays */
    			'description' => __( 'This is the post type for products', 'bonestheme' ), /* Custom Type Description */
    			'public' => true,
    			'publicly_queryable' => true,
    			'exclude_from_search' => false,
    			'show_ui' => true,
    			'query_var' => true,
    			'menu_position' => 5, /* this is what order you want it to appear in on the left hand side menu */
    			'menu_icon' => get_stylesheet_directory_uri() . '/library/images/product-post-icon.png', /* the icon for the custom post type menu */
    			'rewrite'	=> array( 'slug' => 'product', 'with_front' => false ), /* you can specify its url slug */
    			'has_archive' => 'product', /* you can rename the slug here */
    			'capability_type' => 'post',
    			'hierarchical' => false,
    			'taxonomies' => array( 'category'),
    			'register_meta_box_cb' => 'add_album_info_meta_box',
    			/* the next one is important, it tells what's enabled in the post editor
    						 i.e. 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'sticky') */
    			'supports' => array( 'title', 'editor', 'thumbnail', 'sticky')
    	 	) /* end of options */
    	); /* end of register post type */
    
    	/* this adds your post categories to your custom post type */
    	register_taxonomy_for_object_type('category', 'product');
    	/* this adds your post tags to your custom post type */
    	register_taxonomy_for_object_type('post_tag', 'product');
    
    }
    
    // Remove default category and tag box
    function remove_product_default_fields() {
    	remove_meta_box( 'categorydiv' , 'product' , 'side' ); 			// Category Box
    //	remove_meta_box( 'tagsdiv-post_tag' , 'product' , 'side' );		// Tag Box (uncomment to hide)
    }
    add_action( 'admin_menu' , 'remove_product_default_fields' );

    This is where the funny part starts:

    // Save Product to "Products" category
    function save_to_product_category($post_ID) {
    
    	//Create category based on Singular Name
    		$get_cat_name = get_post_type_object( 'product' );
    		$cat_name = $get_cat_name->labels->singular_name;
    		if ( ! category_exists($cat_name) ) {
    			wp_create_category( $cat_name );
    		}
    
    	//Assign post to category
    		global $wpdb;
    		if(wp_is_post_autosave($post_ID) || wp_is_post_revision($post_ID)) {
    		  return $post_ID;
    		}
    		$ccat_id = get_cat_ID( $cat_name );
    		wp_set_object_terms( $post_ID, $ccat_id, 'category' );
    
    }
    
    add_action('publish_product', 'save_to_product_category');
    
    // adding the (custom) product function to the WordPress init
    add_action( 'init', 'product_post');

    CPT works fine. It also creates the category.

    BUT when I save a second Product (aka Custom Post Type) it generates a new Category that is nothing more than a number and assign that post to it...

    Please help me...

    BTW.: This is based on the Bones Theme's Custom Post Type template

    P.S.: I should also mention I'm not a big php expert nor wordpress genius. This is more or less the result of reading a lot in the codex, this forum and google...so sorry if this is a stupid question.

  2. ramco
    Member
    Posted 1 year ago #

    No one? I'm still trying, but totally messed it up...so the code above is still my "most recent" :-(

  3. keesiemeijer
    moderator
    Posted 1 year ago #

    Try changing this:

    $ccat_id = get_cat_ID( $cat_name );

    to this:

    $ccat_id = intval( get_cat_ID( $cat_name ) );

    http://codex.wordpress.org/Function_Reference/wp_set_object_terms

  4. ramco
    Member
    Posted 1 year ago #

    Oh my god! You are a genius!
    I thank you so much!!
    Seems as if it works as it should!! Thank you!

  5. keesiemeijer
    moderator
    Posted 1 year ago #

    You're welcome. I'm glad you've got it resolved :-)

  6. ramco
    Member
    Posted 1 year ago #

    So kessiemeijer's solution works like a charm! Thanks so much again!

    But now I tried to assign my Custom Post to a child-category depending on the so called "Format" given by a Custom Meta Box value.

    I tried the whole day again to achieve this, searched the forums and web, but I found nothing that really helped me...

    This is what I have so far:

    // Save Product to "Products" category
    function save_to_product_category($post_ID) {
    
    	//PARENT CATEGORY
    	//Create parent category based on Singular Name
    		$get_cat_name = get_post_type_object( 'product' );
    		$cat_name = $get_cat_name->labels->singular_name;
    		if ( ! category_exists($cat_name) ) {
    			wp_create_category( $cat_name );
    		}
    
    	//Assign post to parent category
    		global $wpdb;
    		if(wp_is_post_autosave($post_ID) || wp_is_post_revision($post_ID)) {
    		  return $post_ID;
    		}
    		$ccat_id = intval( get_cat_ID( $cat_name ) );
    		wp_set_object_terms( $post_ID, $ccat_id, 'category' );

    This is the part I am searching a solution for

    //CHILD CATEGORY
    	//Create child category based on Format
    		$get_child_cat_name = $post_meta_data['album_info_format'][0];
    		foreach ($get_child_cat_name as $child_cat_string) {
    																    switch($child_cat_string) {
    		//Cassette
    			case 'mc':
    			$child_cat_name = array('Record','Cassette');
    			break;
    		//CD
    			case 'cd':
    			$child_cat_name = array('Record','CD');
    			break;
    		//Vinyl
    			case 'lp':
    			$child_cat_name = array('Record','Vinyl');
    			break;
    		//Digital
    			case 'mp':
    			$child_cat_name = array('Record','Digital');
    			break;
    		//Magazine
    			case 'zine':
    			$child_cat_name = array('Print','Magazine');
    			break;
    		//Print
    			case 'print':
    			$child_cat_name = array('Print');
    			break;
    		//Video
    			case 'video':
    			$child_cat_name = array('Video');
    			break;
    		//Apparel
    			case 'apparel':
    			$child_cat_name = array('Apparel');
    			break;
    		//Textile
    			case 'textile':
    			$child_cat_name = array('Textile');
    			break;
    		//Merch
    			case 'merch':
    			$child_cat_name = array('Merchandise');
    			break;
    		//Other
    			case 'other':
    			$child_cat_name = array('Other Formats');
    			break;
    }
    															}
    		foreach ($child_cat_name as $child_cat_name_string) {
    			if ( ! category_exists($child_cat_name_string) ) {
    				wp_create_category( $child_cat_name_string, $ccat_id );
    			}
    		}
    
    	//Assign post to child category
    		global $wpdb;
    		if(wp_is_post_autosave($post_ID) || wp_is_post_revision($post_ID)) {
    		  return $post_ID;
    		}
    		foreach ($child_cat_name as $child_cat_cat_string) {
    			$child_ccat_id = intval( get_cat_ID( $child_cat_cat_string ) );
    			wp_set_object_terms( $post_ID, $child_ccat_id, 'category' );
    		}
    
    }
    
    add_action('publish_product', 'save_to_product_category');

    The idea is almost the same as it is for the parent category:

    1. Get the "Format" and relate the Categories to that format
    2. Check if there is already such a cat. If not create one under the specified Parent (here: Product)
    3. Assign Custom Post to the Categories

    I hope my code is not such a disaster as it feels like after working on it the whole day without any result...

  7. keesiemeijer
    moderator
    Posted 1 year ago #

    It's difficult to help without seeing all of the code. How do you set the $post_meta_data variable? Is the child category code in the same save_to_product_category function or is this another function?

    Can you paste and submit the full code here or into a pastebin. See the Forum Rules for posting code and using a pastebin.

  8. ramco
    Member
    Posted 1 year ago #

    Sure, my bad, I'm sorry...

    Here is the full code:

    This (http://pastebin.com/ZERUgZ9N)goes in a product-post-type.php that is loaded in the functions.php via require_once('library/product-post-type.php');

    This (http://pastebin.com/ctrAUX9P) is the single-product.php, that will show this "Product"-Custom-Post-Type.

    I'm sorry, this must look terrible. I hope nonetheless it will make things clear.
    Otherwise please let me know, since I still didn't came up with a solution for this task yet.

    Thanks in advance for any help!!

  9. keesiemeijer
    moderator
    Posted 1 year ago #

    Try setting the $post_meta_data variable as you do in single.php. Change this in the save_to_product_categor() function:

    $get_child_cat_name = $post_meta_data['album_info_format'][0];

    to this:

    $post_meta_data = get_post_custom($post_ID);
    $get_child_cat_name = $post_meta_data['album_info_format'][0];
  10. ramco
    Member
    Posted 1 year ago #

    Sorry for delay, I had to work the whole day. And thanks for the reply!!

    I changed the code in the save_to_product_category() function as you said.
    Unfortunately this didn't do the trick...the child category isn't created nor the post filed under it.

    Actually, I don't know exactly what you mean here:

    Try setting the $post_meta_data variable as you do in single.php.

    The child-cat. shall be set to the same value like the checkboxes the user clicked in the edit screen under "Format" (i.e. if you check Cassette the function shall file the post under the "Record" and the "Cassette" category, like specified in the array for this case)
    I store these Format values in album_info_format

    I checked if I hand over a wrong variable or a similar mistake, but I can't see any.
    Do you think the code is too messed up to work with? I really can't tell, since I am far, far, far from being a php programmer...

  11. ramco
    Member
    Posted 1 year ago #

    I'm a step further now, that means, at least the sub-categories are now created upon post-save.

    I just had to unserialize the data from that album_info_format-Array.
    And had to array_push the according values into my $child_cat_name.

    This part of my code ist now:

    $post_meta_data = get_post_custom($post_ID);
    $get_child_cat_name = unserialize($post_meta_data['album_info_format'][0]);
    $child_cat_name = array();
    foreach ($get_child_cat_name as $child_cat_string) {
    	switch($child_cat_string) {
    		//Cassette
    		case 'mc':
    		array_push($child_cat_name,'Record','Cassette');
    		break;
    
    		//CD
    		case 'cd':
    		array_push($child_cat_name,'Record','CD');
    		break;
    	}
    }
    
    foreach ($child_cat_name as $child_cat_name_string) {
    	if ( category_exists($child_cat_name_string) ) {
    		wp_create_category( $child_cat_name_string, $ccat_id );
    	}
    }

    The code is shortened to just two cases within the switch compared to my original code

    What I am struggling now with is that the post is neither assigned to the parent category (which is "Product" in my case) nor to the specified and created child categories BUT the last one in the array...

    My code for this case hasn't really changed yet, since I don't know what to do exactly, where the problem is and everything I tried failed so far.
    The code is:

    //Assign post to child category
    		global $wpdb;
    		if(wp_is_post_autosave($post_ID) || wp_is_post_revision($post_ID)) {
    		  return $post_ID;
    		}
    		foreach ($child_cat_name as $child_cat_cat_string) {
    			$child_ccat_id = intval( get_cat_ID( $child_cat_cat_string ) );
    			wp_set_object_terms( $post_ID, $child_ccat_id, 'category' );
    		}
    
    }

    Anyone?

  12. ramco
    Member
    Posted 1 year ago #

    Alright!
    This was too obvious actually...

    all I had to do, was to add an append to the wp_set_object_term

    So it's now:

    //Assign post to child category
    		global $wpdb;
    		if(wp_is_post_autosave($post_ID) || wp_is_post_revision($post_ID)) {
    		  return $post_ID;
    		}
    		foreach ($child_cat_name as $child_cat_cat_string) {
    			$child_ccat_id = intval( get_cat_ID( $child_cat_cat_string ) );
    			wp_set_object_terms( $post_ID, $child_ccat_id, 'category', true );
    }

    Last thing:
    I realised, that the new created "child categories" aren't actually child-categories, that means that they aren't assigned to a parent upon creation…I don't see why:

    foreach ($child_cat_name as $child_cat_name_string) {
    			if ( ! category_exists($child_cat_name_string) ) {
    				wp_create_category( $child_cat_name_string, $ccat_id );
    			}
    		}

    Since $ccat_id is made to an integer after the generous help of keesiemeijer, should'nt it work like that? I compared wp_create_category to the codex and this way it should assign the created category to a parent with the given ID, shouldn't it?

Topic Closed

This topic has been closed to new replies.

About this Topic