Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Query posts using title as tag WordPress

  • SOLVED

I'm building a single post template for a custom post type "books". In it I want to create a query that grabs a few blog posts that are in a "reviews" category but also tagged with a tag which is identical to the book's title. The catch is, I want this single post template to be re usable for several single books, so the tag can't be hard coded.

If the title of the book is "example", it must grab blog posts with the category of "reviews" and the tag of "example".

Whereas if the book is called "something" it must grab blog posts with the category of reviews and the tag of "something"

Is this even possible? Is there perhaps a different way of approaching the problem?

Answers (2)

2011-03-29

Daniele Raimondi answers:

If the posts you wanna retrieve belongs to the default type 'posts' , create a new wp_query object with these args

$args = array(
'post_type' => 'post',
'category_name' => 'reviews',
'tag' => get_the_title(),
'orderby' => 'date',
'order' => 'DESC',
);
$related_posts = new WP_Query($args);


ah, obviously you have to loop through your results like this

if ( $related_posts->have_posts ):
while ($related_posts->have_posts()) : $related_posts->the_post();
/* echo your data */
endwhile;
endif;

2011-03-29

Andrzej answers:

If I understand correctly, it sounds to be possible. I'd try something like this (you need Wordpress 3.1 to make it work)


$single_post_title = the_title('', '', false);

$query_args = array(
'post_type' => 'post',
'category_name' => 'reviews',
'order' => 'ASC',
'paged' => get_query_var('paged') ? get_query_var('paged') : 1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'post_tag',
'field' => 'term_name',
'terms' => $single_post_title,
'operator' => 'IN',
)
);
);
query_posts( $query_args );

/* your query */

wp_reset_query();