how can I make the search return only single random correct result?

look, i ve searching for a long time that can not find anything about this, but lots of questions about "how to fix the problems like showing only one result"...but the mistake-result they made seems not what i need, because i need to show the Correct Result which hit the keywords, AND, everytime you search, it turn out to be another random result, but not by time or other logics.

Please tell me which file i should change, function.php or search.php? and what code i should add or fix?

Replay

For a relatively small number of posts, you could try the following:

/**
 * Return a single random search result
 */
add_action( 'pre_get_posts', function( \WP_Query $q )
{
    if( ! is_admin() && $q->is_main_query() && $q->is_search() )
    {
        $q->set( 'posts_per_page', 1 );
        $q->set( 'orderby', 'rand' );
    }
} );

where we modify the main front-end search query.

Note that ordering by random doesn't scale well.

Another approach would be to fetch e.g. max 15 posts from the search query, order these posts by random and then display a single one:

/**
 * Return max 15 posts from the search results, ignore paging
 * and then only display a single random post
 */
add_action( 'pre_get_posts', function( \WP_Query $q )
{
    if( ! is_admin() && $q->is_main_query() && $q->is_search() )
    {
        $q->set( 'posts_per_page', 15 );
        $q->set( 'no_found_rows', true ); // ignore paging

        // Display only a single random post from these 15
        add_filter( 'the_posts', 'wpse_random_post' );
    }
} );

/**
 * Return a single random post from the posts results array.
 */
function wpse_random_post( Array $posts )
{
    remove_filter( current_filter(), __FUNCTION__ );

    if( count( $posts ) > 0  )
        $posts = [ $posts[array_rand( $posts )] ];

    return $posts;
}

Category: search Time: 2016-07-29 Views: 0
Tags: search

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.182 (s). 12 q(s)