WordPress.org

Make WordPress Core

Opened 4 years ago

Closed 21 months ago

#34766 closed defect (bug) (worksforme)

Order by rand in taxonomy page don't work

Reported by: sebastian.pisula Owned by:
Milestone: Priority: normal
Severity: normal Version:
Component: Query Keywords: reporter-feedback
Focuses: Cc:

Description

I use filter:

<?php
add_action( 'pre_get_posts', 'hook' );
function hook( $query )
{
    /** @var WP_Query $query */
    if ( $query->is_main_query() && $query->is_tax( 'landing-page-highlight', 'special-offer' ) ) {
        $query->set( 'posts_per_page', -1 );
        $query->set( 'orderby ', 'rand' );
    }
}

Query Monitor show that order is random. If I use WP_Query in taxonomy.php template then this work:

<?php
global $wp_query;

$term = $wp_query->queried_object;

$args = array(
                'orderby'        => 'rand',
                'posts_per_page' => - 1,
                'post_type'      => 'landing-page',
                'tax_query'      => array(
                                array(
                                                'taxonomy' => $term->taxonomy,
                                                'field'    => 'slug',
                                                'terms'    => $term->slug,
                                )
                )
);


$wp_query = new WP_Query( $args );

?>

And My register taxonomy:

<?php
register_taxonomy( 'landing-page-highlight', array( 'landing-page' ), array(
        'labels'            => array(),
        'hierarchical'      => true,
        'public'            => true,
        'show_ui'           => true,
        'show_admin_column' => true,
        'show_in_nav_menus' => true,
        'show_tagcloud'     => false,
        'rewrite'           => array(
            'slug'         => 'product',
            'with_front'   => true,
            'hierarchical' => true,
        ),
    ) );

Change History (3)

#1 @swissspidy
4 years ago

  • Component changed from General to Query
  • Keywords reporter-feedback added

Just to clarify, when using new WP_Query(…) normally, 'orderby' => 'rand' works perfectly, but when hooking into pre_get_posts it doesn't. Correct?

Are you sure your filter is run correctly? What happens when you remove the if ( $query->is_main_query() && $query->is_tax( 'landing-page-highlight', 'special-offer' ) ) { condition?

#2 @swissspidy
3 years ago

Hi @sebastian.pisula, any update on this? Is it still an issue? See also my questions from above.

#3 @wonderboymusic
21 months ago

  • Milestone Awaiting Review deleted
  • Resolution set to worksforme
  • Status changed from new to closed

No feedback here

Note: See TracTickets for help on using tickets.