0

I have an e-commerce shop. I am new to php and wordpress. (I have a python and ruby background though, I just don't know php)

And I have a page with items. Right now the last 20 items are displayed on page (or something like this). But I want to show not the last, but items in random order from this category. This is code that lists items in archive.php file:

<?php echo category_description( get_category_by_slug('category-slug')->term_id ); ?></div>
<?php $col = 1;  $counter = 0;?>

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <?php ++$counter;?>
         .......

This code is not written by me. I clicked go to definition on have posts() function and got to this in wp-includes/class-wp.query.php

* @return bool True if posts are available, false if end of loop.
     */
    public function have_posts() {
        if ( $this->current_post + 1 < $this->post_count ) {
            return true;
        } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
            /**
             * Fires once the loop has ended.
             *
             * @since 2.0.0
             *
             * @param WP_Query $this The WP_Query instance (passed by reference).
             */
            do_action_ref_array( 'loop_end', array( &$this ) );
            // Do some cleaning up after the loop
            $this->rewind_posts();
        } elseif ( 0 === $this->post_count ) {
            /**
             * Fires if no results are found in a post query.
             *
             * @since 4.9.0
             *
             * @param WP_Query $this The WP_Query instance.
             */
            do_action( 'loop_no_results', $this );
        }

        $this->in_the_loop = false;
        return false;
    }

Also when I clicked go to definition it suggested me second option in file: query.php

 * @since 1.5.0
 *
 * @global WP_Query $wp_query Global WP_Query instance.
 *
 * @return bool
 */
function have_posts() {
    global $wp_query;
    return $wp_query->have_posts();
}

What do I do?

  • Do you need pagination? Random sorting of posts isn’t really feasible if you require pagination. – Jacob Peattie May 31 '18 at 15:47
  • not really =just 20 random results from current category – user2950593 May 31 '18 at 16:16
1

You need a custom query. codex ref

For instance,

$args = array(
    'orderby'        => 'rand',
    'posts_per_page' => 20,

);
$query = new WP_Query( $args );

this query pick 20 random items. If you go above link, you can see more examples. I hope this will help you.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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