Auto add category based on a mapped tag

Support MB Relationships Auto add category based on a mapped tag

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #36192
    jak93jak93
    Participant

    Hi, first of all i'm not a programmer 🙁 i would like to auto add a specific category when a tag is added to a custom post, so i basically created a term MB Relationship from tag to category then i know i need to code but i don't know where to start, if somebody can help... thanks

    #36207
    Long NguyenLong Nguyen
    Moderator

    Hi,

    I think no need to use the extension MB Relationship in your case. You can create a custom function to check if the post has a tag ID and then set the category for the post and hook this function to the action save_post. For example:

    add_action( 'save_post', 'set_post_category', 10,3 );
     
    function set_post_category( $post_id, $post, $update ) {
      // Only want to set if this is a new post!
      if ( $update ){
          return;
      }
       
      // Only set for post_type = post!
      if ( 'post' !== $post->post_type ) {
          return;
      }
    
      $posttags = get_the_tags( $post_id );
      if ( $posttags ) {
        foreach( $posttags as $tag ) {
          if( $tag->term_id == 12 ) {
            wp_set_post_categories( $post_id, [34, 56], true);
          }
        }
      }
    }

    where 12 is the tag ID, and 34, 56 is the category IDs.

    Read more on the documentation
    https://developer.wordpress.org/reference/hooks/save_post/
    https://developer.wordpress.org/reference/functions/get_the_tags/
    https://developer.wordpress.org/reference/functions/wp_set_post_categories/

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.