我怎样才能将这些帖子随机化

时间:2016-02-07 01:26:45

标签: php wordpress

以下长代码块是我的taxonomy-product-category.php模板。我想要循环加载的帖子随机排序。我可能需要在循环开始之前的某个地方实现一行代码,但是我无法解决它并且让我困扰很多。我尝试添加<?php query_posts('orderby=rand'); ?>,但它只是使所有帖子看起来都是空的(空的和有缺陷的)

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

<li class="box" id="post-<?php the_ID(); ?>">

    <?php $disc = get_post_meta($post->ID, 'fabthemes_discount', true); ?>

    <?php if ( $disc ) { ?>

            <span class="salebadge"></span>

    <?php }?>



        <a href="<?php the_permalink() ?>"><img class="productshot" src="<?php get_image_url(); ?>" alt=""/></a>



        <div class="pricetab clearfix">



        <?php if ( $disc ) { ?>

            <span class="oldprice"><del> <?php echo get_post_meta($post->ID, 'fabthemes_disc-price', true) ?> </del></span>

        <?php }?>



        <span class="prodetail"><a href="<?php the_permalink() ?>"><?php $price=get_post_meta($post->ID, 'fabthemes_price', true); echo $price; ?></a></span>

        </div>

    </li>
<?php endwhile; ?>
</ul>
<div id="home-content2" class="clearfix">
<h1 align="center"><b>Google</b> Hedeflenen Kelimelerimiz Hakkında Makalemiz</h1>
<?php if ( $paged < 2 ) { ?>
<?php echo category_description( $category_id ); ?> 
<?php } ?>
</div>

<?php getpagenavi(); ?>

<?php else : ?>

    <h1 class="title">Üzgünüz</h1>
    <p>Henüz bu kategoride ilan verilmemiş.</p>

<?php endif; ?>

</div>
<?php get_footer(); ?>

1 个答案:

答案 0 :(得分:1)

这样做:

// Put this line at the top of your `taxonomy-product-category.php` file
$the_query = new WP_Query('orderby=rand&posts_per_page='.$home_count.'&post_type=products&paged='.$paged);

删除&order=ASC部分。

然后在您的taxonomy-product-category.php页面中,您可以根据需要更改查询:

if( $the_query->have_posts() ){
    while( $the_query->have_posts() ){
        $the_query->the_post();
        the_title(); // echo the title...
    } 
}

使这样的查询更好(虽然它不会对结果进行任何更改,但更容易阅读)

$the_query = new WP_Query(
    array(
        'orderby'         => 'rand',
        'posts_per_page'  => $home_count,
        'post_type'       => 'products',
        'paged'           => $paged
    )
);

更新

taxonomy-product-category.php文件:

<?php
$home_count = // **You should define this variable here**
$paged = // **You should define this variable here**

$the_query = new WP_Query(
    array(
        'orderby'         => 'rand',
        'posts_per_page'  => $home_count,
        'post_type'       => 'products',
        'paged'           => $paged
    )
);

get_header();

if( $the_query->have_posts() ){
    while( $the_query->have_posts() ){
        $the_query->the_post();?>
        <h1><?php the_title();?></h1>
        <a href="<?php the_permalink() ?>"><img class="productshot" src="<?php get_image_url(); ?>" alt=""/></a><?php
    } 
}

get_footer();
?>