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

Query Rand Posts from CPT based on Tag. WordPress

  • SOLVED

<strong>Overview:</strong>
Hello, I would like to associate random quotes with particular services by using tags. I have a CPT type called 'Quotes' within I will have various postings with tags.

I would like these tagged postings to display randomly on the sidebar of various cpt's, posts or pages based on the tag defined on the particular page.

<strong>Details:</strong>
I enabled tags on CPT's, Posts and Pages. I require assistance writing a function that detects a page, post or cpt tags and stores that information and echoes that into my random query.

<strong>Code Sample:</strong>
<?php $posttags = get_the_tags(); if ($posttags) { foreach($posttags as $tag) { echo $tag->name . ', '; } } ?>
<?php query_posts(array('post_type' => 'quotes', 'tags' => '$TAG', 'posts_per_page' => 1, 'orderby' => 'rand',)); if (have_posts()) while (have_posts()) : the_post(); the_content('');?>
<?php endwhile; wp_reset_query();?>


<em>Any assistance you can provide would be much appreciated!</em>

Answers (2)

2011-12-30

Jurre Hanema answers:

I think this should get you started:


<?php

$posttags = get_the_tags();

$posttags = wp_list_pluck($posttags, 'term_id');

query_posts(
array(
'post_type' => 'quotes',
'posts_per_page' => 1,
'orderby' => 'rand',
'tag__in' => $posttags
)
);

while(have_posts())
{
the_post();
the_content('');
}

wp_reset_query();

?>

2011-12-31

Arnav Joy answers:

in your sidebar.php get the tags associated with the post , page or cpt and then use this tags to search quotes

try this
<?php
global $post;

$t = wp_get_post_tags($post->ID);

$t = implode('+',$t);


query_posts( 'post_type=quotes&tag='.$t );

while(have_posts())

{

the_post();

the_content('');

}



wp_reset_query();

?>