Monday, 5 March 2012

How to get the posts by post tags in wordpress

We have easily get the post titles from from the post Id. So We have to try to get the post Id using the post tags.

<?php 
               
global  $wpdb;

$postTags = "Accidents";

//Below query can be used to get the post id using post tags.

$querystr ="SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id = (SELECT term_taxonomy_id FROM wp_term_taxonomy WHERE taxonomy = 'post_tag' AND term_id = (SELECT term_id FROM wp_terms WHERE name ='$postTags '))";

$result= $wpdb->get_results($querystr);
//$result have the post id. Now we easily get the post title or post information using post id.

foreach($result as $postid) {

echo get_the_title($postid->object_id).'<br/>';

}

?>