contact support' ); } $where = array( "post_password = ''", "post_status = 'publish'", ); $where_args = array(); // Set default post type. $post_type = get_post_type(); // Change the post type if the parameter is set. if ( isset( $_GET['random_post_type'] ) && post_type_exists( sanitize_key( $_GET['random_post_type'] ) ) ) { $post_type = sanitize_key( $_GET['random_post_type'] ); } // Don't show a random page if 'page' isn't specified as the post type specifically. if ( 'page' === $post_type && is_front_page() && ! isset( $_GET['random_post_type'] ) ) { $post_type = 'post'; } $where[] = 'p.post_type = %s'; $where_args[] = $post_type; // Set author name if we're on an author archive. if ( is_author() ) { $where[] = 'post_author = %s'; $where_args[] = get_the_author_meta( 'ID' ); } // Set default category type if ( is_category() ) { $category = get_the_category(); if ( isset( $category ) && ! empty( $category ) ) { $random_cat_id = $category[0]->term_id; } } // Set the category ID if the parameter is set. if ( isset( $_GET['random_cat_id'] ) ) { $random_cat_id = (int) $_GET['random_cat_id']; } global $wpdb; $where = implode( ' AND ', $where ); // Pick a post via COUNT plus a random OFFSET rather than ORDER BY RAND(), which randomizes and sorts every candidate row on each request. if ( isset( $random_cat_id ) ) { $from_where = "FROM $wpdb->posts AS p INNER JOIN $wpdb->term_relationships AS tr ON (p.ID = tr.object_id AND tr.term_taxonomy_id = %s) INNER JOIN $wpdb->term_taxonomy AS tt ON(tr.term_taxonomy_id = tt.term_taxonomy_id AND taxonomy = 'category') WHERE $where"; $query_args = array_merge( array( $random_cat_id ), $where_args ); } else { $from_where = "FROM $wpdb->posts AS p WHERE $where"; $query_args = $where_args; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare $post_count = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( DISTINCT p.ID ) $from_where", ...$query_args ) ); if ( $post_count < 1 ) { return; } $query_args[] = wp_rand( 0, $post_count - 1 ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare $random_id = $wpdb->get_var( $wpdb->prepare( "SELECT DISTINCT p.ID $from_where ORDER BY p.ID LIMIT 1 OFFSET %d", ...$query_args ) ); if ( ! $random_id ) { return; } // @phan-suppress-next-line PhanTypeMismatchArgument $permalink = get_permalink( $random_id ); wp_safe_redirect( $permalink ); exit( 0 ); } add_action( 'template_redirect', 'jetpack_matt_random_redirect' ); }