0

I use a third-party plugin that creates custom posts (adverts) from the front-end in two steps: 1) after the content adding the author must push a "Preview" button and 2) only after that he/she already can save the post. After the first step the post is saved with a pending (advert_tmp) status, and after the second he become "publish"-ed.

This is what I want: between these two steps to convert/save a meta_key values as the post tags. After some research I came to the next partially working function:

add_action('save_post', 'set_advert_tags');
function set_advert_tags( $post_id ) {
   if ( 'advert' == get_post_type() ) {
      $tags = get_post_meta( $post_id, 'advert_tags_field', true );
      $tags = explode( ',', $tags );
      if(!empty( $tags ))
         wp_set_object_terms( $post_id, $tags, 'advert_tag' );
   }
}

What is wrong: the function doesn't create tags nor after the first step, nor after the second step, but it works when I update the post from the back-end. And here I have another problem: I can't add or assign new tags to the post from the back-end because my function disturb somehow this action, only the meta_key values are assigned as post tags.

1 Answer 1

0

The @PieterGoosen's answer saved my life:

add_action( 'transition_post_status', function ( $new_status, $old_status, $post ) {
   if( 'publish' == $new_status && 'advert_tmp' == $old_status && $post->post_type == 'advert' ) {
      $tags = get_post_meta( $post->ID, 'advert_tags_field', true );
      $tags = explode( ',', $tags );
      if( !empty( $tags ) ) {
         wp_set_object_terms( $post->ID, $tags, 'advert_tag' );
         delete_post_meta( $post->ID, 'advert_tags_field' );
      }
    }
}, 10, 3 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.