WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Get post tags for multiple posts (2 posts)

  1. Rebecca Schaefer
    Member
    Posted 5 years ago #

    I want to get a list of tags from multiple posts. I see wp_get_post_tags, which accepts a single post ID.

    Does anyone know of any function that will retrieve tags for an array of post IDs? I need to save on queries.

  2. Rebecca Schaefer
    Member
    Posted 5 years ago #

    In case anyone ever comes across this problem, I found the function in taxonomy.php.

    I was selecting specific categories from the database then looping through them. $term->term_id is the ID of the current category in the loop.

    // Select all the posts in that category
    $posts		=	get_posts(array('category' => $term->term_id));
    $post_ids	=	array();
    
    // iterate through the array returned by get_posts, and add the ids to its own array
    foreach($posts AS $post) {
    	$post_ids[]	=	$post->ID;
    }
    
    // pass the array of post ids to wp_get_object_terms, from taxonomy.php. Also specify that it should return post_tags.
    $tags		=	wp_get_object_terms($ids, 'post_tag');
    $tags_names	=       array();
    
    // iterate through the tags returned by wp_get_object_terms
    // there are other fields available, I just only needed the name
    foreach($tags AS $tag) {
    	$tag_names[]	=	$tag->name;
    }
    
    // create a comma delimited list of tag names
    $tags		=	implode(', ', $tag_names);

Topic Closed

This topic has been closed to new replies.

About this Topic