• I have a class to add a list of terms to a post when it turns from draft to publish. The function is correctly triggered and the code (now, because I have commented almost all lines) is as simple as this:

    class setCategoriesRight
    {
        public function __construct()
    	{
            add_action( 'draft_to_publish', array( $this, 'publish_post' ) );
        }
    
        public function publish_post($post)
    	{
            if('myposttype' == $post->post_type) //Si pertenece al custom post type agencia o experto
    		{
    			$post_id = $post->ID;
    			$categories = array(11, 12, 13, 14, 15);
    			wp_set_post_categories( $post_id, $categories, true);
    		}
    	}
    }
    new setCategoriesRight;

    After the function is fired, the wp_term_relationship table is completely unaltered.
    What I’m doing wrong?

Viewing 7 replies - 1 through 7 (of 7 total)
  • Thread Starter leandro_S

    (@leandro_s)

    Any hint will be welcome, I feel very stuck with this!

    Thread Starter leandro_S

    (@leandro_s)

    So nothing seems to be wrong in my code?
    I still haven’t found how to fix this.
    In the codex there are no examples for wp_set_post_categories() neither…

    Moderator bcworkz

    (@bcworkz)

    Your code works fine for me on my installation. I only changed the post type slug and category IDs to work with my installation.

    You probably have a theme or plugin conflict that’s preventing your code from working. To locate the problem disable all plugins and swap to a default theme. Place your code temporarily in twentyfifteen’s functions.php (or a stand alone plugin) Your code should work.

    Re-enable your theme, then each plugin one at a time. When your code stops working you’ve found the conflict.

    BTW. you kind of screw yourself by bumping. Most of the true experts here use the no replies filter to see who still needs help. Once you bump, you fall off the filtered list. The people best suited to help you never see your post! I became curious when I saw you answered a few other topics. Thanks for helping out, that is what led me here ??

    Thread Starter leandro_S

    (@leandro_s)

    You are so kind, bcworkz!!
    I’ve been stuck with this all day long, tomorrow I will disable all plugins and see which one is messing with my function. I guess it has to be Types, as is the one which messes deeper with this kind of functions.
    If that were the case, what can I do afterwards?
    I will need Types and I will also need my function working…

    Thanks for your help!

    Moderator bcworkz

    (@bcworkz)

    If the conflicting plugin or theme is something you cannot live without, you could simply report it to the author, but that will not necessarily solve your problem if they cannot replicate the issue. So it would pay for you to do further debugging.

    Look through the code for any possible name conflicts. Also look at any action or filter hooks that may be in common or related to your code – anything to do with saving posts or term relationships. Comment out anything that might cause a conflict and see if your code then works. If you get far enough to find the conflicting function or hook, you can probably see exactly what is causing the problem in the function’s code just by examination.

    Then you can patch the code and report that specific issue to the author. Or do something to your code to remove the conflict if that is a possibility. It’s all mainly a process of methodical elimination, each iteration reduces where the problem lies until the range is so small the glitch can be identified on sight or with some simple debugging. It can be very time consuming, requiring much patience and perseverance. Good luck!

    Thread Starter leandro_S

    (@leandro_s)

    I’m still stuck on trying to attach terms to a post.
    I have deactivated all plugins but Types, if I deactivate Types I can’t trigger the draft to publish event as I don’t have the custom post type in my menu anymore. The code works till the first ‘wp_get_post_terms’ arises, then it dies with no error. If somebody can tell me about another way to trigger the function (keeping the post in scope) I will deactivate Types too.
    In the meantime, can somebody check this code? It comes full of comments:

    function publish_post($post)
    {
    	if('my_category' == $post->post_type) //If post belongs to my_category
    	{
    		$post_id = $post->ID;
    
    		$terms = get_post_custom_values('wpcf-my_category', $post_id);//We take the tags given in the custom post type
    
    		$terms = explode(',', $terms[0]);//They where inserted as a string so we transform them in to an array to iterate
    
    		if(is_array($terms))//We check that it is a real array (becaming really paranoid)
    		{
    			for($x = 0; $x < count($terms); $x++)//Loop array elements
    			{
    				$term_id = term_exists( $terms[$x]);//Lets see if the terms already exist as terms
    
    				if ($term_id !== 0 && $term_id !== null)//If term exists we will only attach it to the post
    				{
    					$term_list = wp_get_post_terms($post_id, 'my_category', array("fields" => "term_id"));//Let's check if they are attached already
    
    					if(!in_array($term_id, $term_list))//If they are not attached we do
    					{
    
    						$term_taxonomy_ids = wp_set_post_categories((int)$post_id, (int)$term_id, true);//Here comes the nightmare
    
    						if ( is_wp_error( $term_taxonomy_ids ) )
    						{
    							echo 'Categories have been added';// There was an error somewhere and the terms couldn't be set.
    						}
    						else
    						{
    							echo 'Error adding categories';// There was no error, but the terms haven't ben set
    						}
    					}
    				}
    				else//If term doesn't exists we will create them and get their ID back
    				{
    					$term_object = wp_insert_term(
    					$terms[$x], // the term
    					'my_category', // the taxonomy
    					array(
    						'description'=> '',
    						'slug' => slugify($terms[$x])
    						)
    					);//After inserting with wp_insert_term we should have an objcet back
    
    					$term_id = $term_object['term_id'];//From this object we get the ID
    
    					$term_taxonomy_ids = wp_set_object_terms((int)$post_id, (int)$term_id, 'my_category', true);//We set the terms
    
    					if ( is_wp_error( $term_taxonomy_ids ) )
    					{
    						echo 'Categories have been added';// There was an error somewhere and the terms couldn't be set.
    					}
    					else
    					{
    						echo 'Error adding categories';// Success! The post's categories were set.
    					}
    				}
    			}
    		}
    	}
    }
    Moderator bcworkz

    (@bcworkz)

    The problem with wp_get_post_terms() is the arguments “fields” parameter, the value should be “ids”, not “term_id”. Easy mistake, one would think to pass the column name, but no, it’s an arbitrary value that’s translated to the column name internally by the function.

    So you have both a post_type AND a taxonomy, both called “my_category”? That should not be a problem for WP, but it’s confusing the crap out of me! Even just the taxonomy “my_category” can be a bit confusing next to the default “category” taxonomy.

    Evidence: You’re trying to set “my_category” term IDs to a post as though they are “category” term IDs. wp_set_post_categories() is ONLY for the “category” taxonomy. You must use wp_set_object_terms() for custom taxonomies. Fixing this will probably solve your main problem.

    Further confusion could result because your echo messages do not match up with the expected state when they are output. They appear reversed, I think you’re missing the NOT operator (!) before is_wp_error(). But then your associated comments make sense without the ‘!’, but no one sees comments when the code is run. You best get this coordinated for your own sanity if not mine ??

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘wp_set_post_categories does nothing’ is closed to new replies.