Search code examples
phpwordpresstaxonomycustom-taxonomytaxonomy-terms

Add Post Tags Taxonomy automatically from Post Genre Taxonomy


I created a custom WordPress Post Taxonomy called “genre”

And Is it possible to add post genres Taxonomy values in post tags meta field automatically after saving/publishing post.

Means if i added “File Manager” and “Tools” genre in post then the same thing also goes added in post tags field automatically after Publishing/saving post.

And I also want to prepend “Android” and Append “Download” word in that tags that’ll added from that Genre Taxonomy.

I tried below code but not working properly if i add multiple Genre in post because all generes combines together and makes a single tag:

add_action('save_post','getags');
function getags($post_id) {
    $taxonomy = 'post_tag';
    $terms = 'Android'.get_the_term_list( $post_id, 'genre').'Download';
 return wp_set_object_terms($post_id, $terms, $taxonomy);
}

Solution

  • You may use the save_post hook, and loop through your current terms with the get_the_terms() function.

    add_action('save_post','getags');
    function getags($post_id) { 
      $genres = get_the_terms( $post_id, 'genre');
      $taxonomy = 'post_tag'; 
      foreach($genres as $genre) {
        $terms = 'Android '.$genre->name.' Download'; 
        wp_set_object_terms( $post_id, $terms, $taxonomy, true );
      } 
    }
    
    

    get_the_term_list() is used to retrieve a list of terms. get_the_terms() gives you an array, easier to use.