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

Conditional code to show a query if a category has posts WordPress

  • SOLVED

Hello,

For a Alert News Ticker, I need to create a conditional code that show this code only if the category has an asigned post. If the category is empty, hide the code (from the <ul> to the </ul>.



<ul id="js-news" class="js-hidden">
<?php $my_query = new WP_Query("showposts=10&cat=19");
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li class="news-item"><a href="<?php the_permalink() ?>"><?php the_title() ?></a></li>
<?php endwhile; ?>
</ul>


Thanks!

Answers (3)

2013-09-05

Navjot Singh answers:

Try


if (get_category('19')->category_count > 0)
{
<ul id="js-news" class="js-hidden">
<?php $my_query = new WP_Query("showposts=10&cat=19");
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li class="news-item"><a href="<?php the_permalink() ?>"><?php the_title() ?></a></li>
<?php endwhile; ?>
</ul>
}


No Mind comments:

This is my favourite! Thanks!


No Mind comments:

Where can I vote your response?


Navjot Singh comments:

There is an option Assign prize money beneath the question. Procedure is mentioned here: http://blog.tailormadeanswers.com/2011/04/22/voting-assign-prize-money/


Navjot Singh comments:

Ah its "Vote to award prize" link right under the question. Not Award prize. my bad.

2013-09-05

Arnav Joy answers:



I am assuming you are using this code in category.php , so use it with in loop

<?php
$post_id = 1; // your post id

if( get_the_ID() == $post_id ) { ?>

<ul id="js-news" class="js-hidden">

<?php $my_query = new WP_Query("showposts=10&cat=19");

while ($my_query->have_posts()) : $my_query->the_post(); ?>

<li class="news-item"><a href="<?php the_permalink() ?>"><?php the_title() ?></a></li>

<?php endwhile; ?>

</ul>

<?php } ?>


Arnav Joy comments:

otherwise post your full code where you are using this code

2013-09-05

Abdelhadi Touil answers:

Hi.
Try this:

<?php $my_query = new WP_Query("posts_per_page=10&cat=19");
if ($my_query->have_posts()){ ?>
<ul id="js-news" class="js-hidden">
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li class="news-item"><a href="<?php the_permalink() ?>"><?php the_title() ?></a></li>
<?php endwhile; ?>
</ul>
<?php } ?>


Abdelhadi Touil comments:

Notice that I'v changed "showpost" by "posts_per_page" because posts_per_page replaced showposts parameter since wordpress 2.1.

[[LINK href="http://codex.wordpress.org/Class_Reference/WP_Query"]]http://codex.wordpress.org/Class_Reference/WP_Query[[/LINK]]