简体   繁体   中英

Display posts that belong to certain category - Wordpress

I'm having trouble getting this to work. Can someone provide a quick snippet for category template that displays posts that belong to a category called 'Product A'. I've been using the trial and error method for the past 3 hours with no luck.

Thank you!

Here's what I've been playing around with -

<?php
/*
Template Name: yadayada
*/
?>

<?php get_header(); ?>
<?php get_sidebar(); ?>

<?php query_posts('cat=32&showposts=5'); ?>
<div class="post">

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>


<div <?php post_class() ?> id="post-<?php the_ID(); ?>">
<div class="post-description">
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
</div>
</div>


<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>


</div>

You can used the WP_Query class. One way I've done it before is by first creating a category name of Product-A and making the slug 'product-a' all lower case.

Then instantiate a new instance of the class. Pass in the parameter of 'category_name=product-a' You do no pass in the category name with this parameter, but rather the slug name. once you do that you should be able to use the WP_Query as follows:

<?php $my_query = new WP_Query( 'category_name=product-a' ); ?>
    <?php if ($my_query->have_posts() ) : ?>
        <?php while ( $my_query->have_posts()) :  $my_query->the_post()  ?>  
            <article <?php post_class() ?> id="post-<?php the_ID(); ?>">
                <h2><?php the_title(); ?></h2>
                <div class="product-excerpt"><?php the_content(); ?> </div>
            </article>
        <?php endwhile; ?>           
        <?php else : ?>
            <h2>Not Found</h2>       
    <?php endif; ?>

pretty much everything is the same as the regular loop but instead of just

<?php if(have_post()) : while(have_post()) : the_post() ?>

You would used object notation to refer to this particular query.

<?php if($my_query->have_post()) : while($my_query->have_post()) : $my_query->the_post() ?>

hope it helps.

First get your Product A category id; (if you use, your cat id in your custom query it 's gonna work perfectly instead of category name.)

<?php
query_posts('cat=1');
while (have_posts()) : the_post();
the_content();
endwhile;
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM