0

I am trying to make use of the Single template for single posts ( I have a custom one). But for some reason my posts get overridden instead of displaying new data.

This is the setup I have right now

<div class="details">
<?php global $post;
 $category_id=get_the_category($post->ID);

$announcements = new WP_Query(); 
$announcements->query('showposts=1&cat=$category_id');
while ( $announcements->have_posts() ) :  $announcements->the_post(); ?>  

    <p><strong>Published by:<span itemprop="publisher"><?php echo 
get_post_meta($post->ID, 'Publisher','true');?></strong></p>

<?php endwhile;?>
</div>
1
  • Why anyway are you doing a second query.
    – kaiser
    Commented Jul 11, 2013 at 10:46

3 Answers 3

1

But for some reason my posts get overridden instead of displaying new data.

The problem is here: $announcements->query('showposts=1&cat=$category_id');

You are trying to use a variable inside a single quote string. Variables do not expand inside single quotes so instead of asking for cat=1, or cat=2, you are literally asking for cat=$category_id-- just like that, spelled out in full.

What you need instead are double quotes: $announcements->query("showposts=1&cat=$category_id");. Variables do expand in double quote.

Or better, an array-- far more readable and maintainable:

$args = array(
  'posts_per_page' => 1,
  'cat' => $category_id,
);

Note: showposts is deprecated. Use posts_per_page.

0

You need to Pass arguments into the new Object like so.

$category_id = get_the_category( $post->ID );

$args = array(
    'posts_per_page' => 1,
    'category'       => $category_id
);

$announcements = new WP_Query( $args ); 

This page should shine some light on your code for you, I think you've got a few typo's within it and how you call the loop is in the slightly wrong order. WP_Query in Codex.

0

I tried that, but it still overrides for instance

the_title(), get_post_meta($post->ID, 'key', 'true'), the_post_thumbnail(),

and pretty much all of them gets overriden(What I mean is when I make two posts using the same template, the fields, titles and images get overridden.) Here is how I did it:

<?php
$category_id = get_the_category( $post->ID ); $args =  

array('posts_per_page' => 1, 'category' => $category_id); $announcements = 
new WP_Query( $args );

while($announcements->have_posts()): $announcements->the_post();

?>
<div class="cover"><?php the_post_thumbnail(); ?></div>
<p><strong><span itemprop="title"><?php the_title();?></span></strong></p>
</div>

<?php endwhile;?>
2
  • Answer for @kaiser below. Commented Jul 11, 2013 at 12:01
  • Answer are not threaded, @Johnny. Commented Jul 11, 2013 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.