빈 검색은 홈페이지를 반환합니다. 어떻게 찾을 수없는 검색 페이지를 반환합니까?


16

검색 양식이 비어 있으면 기본 검색 기능이 홈 페이지를 반환하고 "검색 결과가 반환되지 않았습니다"페이지를 반환하려고합니다.

이 게시물은 대답하지 않습니다

그리고 이 티켓은 이 기능에 그런 식으로되어 있는지 알려줍니다! 누구나 .htaccess 리디렉션을 사용하는 것 외에 변경하는 방법을 알고 있습니까?

다음 search.php 파일을 사용하고 있습니다 :`

        <div id="content" class="clearfix">

            <div id="main" class="col700 left clearfix" role="main">

                <h1 class="archive_title"><span>Search Results for:</span> <?php echo esc_attr(get_search_query()); ?></h1>

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

                <article id="post-<?php the_ID(); ?>" <?php post_class('clearfix'); ?>>

                    <header>

                        <h3><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h3>

                        <p class="meta"><?php _e("Posted", "bonestheme"); ?> <time datetime="<?php echo the_time('Y-m-j'); ?>" pubdate><?php the_time('F jS, Y'); ?></time> <?php _e("by", "bonestheme"); ?> <?php the_author_posts_link(); ?> <span class="amp">&</span> <?php _e("filed under", "bonestheme"); ?> <?php the_category(', '); ?>.</p>

                    </header> <!-- end article header -->

                    <section class="post_content">
                        <?php the_excerpt('<span class="read-more">Read more on "'.the_title('', '', false).'" &raquo;</span>'); ?>

                    </section> <!-- end article section -->

                    <footer>


                    </footer> <!-- end article footer -->

                </article> <!-- end article -->

                <?php endwhile; ?>  

                <?php if (function_exists('page_navi')) { // if expirimental feature is active ?>

                    <?php page_navi(); // use the page navi function ?>

                <?php } else { // if it is disabled, display regular wp prev & next links ?>
                    <nav class="wp-prev-next">
                        <ul class="clearfix">
                            <li class="prev-link"><?php next_posts_link(_e('&laquo; Older Entries', "bonestheme")) ?></li>
                            <li class="next-link"><?php previous_posts_link(_e('Newer Entries &raquo;', "bonestheme")) ?></li>
                        </ul>
                    </nav>
                <?php } ?>          

                <?php else : ?>

                <!-- this area shows up if there are no results -->

                <article id="post-not-found">
                    <header>
                        <h1>No Results Found</h1>
                    </header>
                    <section class="post_content">
                        <p>Sorry, but the requested resource was not found on this site.</p>
                    </section>
                    <footer>
                    </footer>
                </article>

                <?php endif; ?>

            </div> <!-- end #main -->

            <div id="sidebar1" class="sidebar right col220">

                <?php get_search_form(); ?>



            </div>

        </div> <!-- end #content -->

`


코드를 보여?
— 카이저

이 문제를 해결하기 위해 어디에서 시작 해야할지조차 모르므로 (htaccess 제외) 코드가 없습니다. 도움을 주셔서 감사합니다
— Drai

searchform.php와 search.php 코드는 어떻습니까?
— 카이저 September

search.php가있는 본즈 테마를 사용하고 있지만 핵심 검색 형식을 사용합니다
— Drai

2
이것은 테마별 문제가 아닌 일반적인 WordPress 문제입니다.
— Tom J Nowell

답변:


18

여기 에이 문제를 해결하는 3 가지 방법이 있습니다. 솔루션 2를 사용하는 것이 좋지만 처음에는 상황을 피하는 방법으로 솔루션 1의 jQuery에주의하십시오.

질문자 테마에서 더 많은 코드를 게시하려는 사람들에게는 이것이 테마 문제가 아니며 모든 WordPress 사이트에 영향을 미치는 일반적인 WordPress 문제입니다.

해결책 1

이 문제를 해결하는 방법에 대한 심층 자습서를 찾을 수 있습니다.

http://wpengineer.com/2162/fix-empty-searches/

오늘날 대부분의 전문가가 볼 수없는 빈 검색 : 검색 입력 필드를 제공하면 아무 용어도 입력하지 않고 누군가가 실수로 제출 버튼을칩니다. 결과 URI는 example.com/?s=와 같습니다. 프론트 페이지와 동일한 내용을 보여줍니다. 실제로 첫 페이지입니다.

아무도 필요하지 않습니다.

솔루션 2 (권장)

Spitzerg가 게시 한 글 http://wordpress.org/support/topic/blank-search-sends-you-to-the-homepage

다른 옵션은 요청 필터를 추가하는 것입니다.

add_filter( 'request', 'my_request_filter' );
function my_request_filter( $query_vars ) {
    if( isset( $_GET['s'] ) && empty( $_GET['s'] ) ) {
        $query_vars['s'] = " ";
    }
    return $query_vars;
}

그런 다음 검색 양식에서 검색 쿼리를 재사용하는 경우 하나 이상의 공백으로 끝나지 않도록 정리하십시오 (물건을 유지하기 만하면 결과에 영향을 미치지 않음).

<input type="text" name="s" id="s" value="<?php echo trim( get_search_query() ); ?>"/>

이것이 도움이되기를 바랍니다. 지금까지 내 사이트에서 작동하는 것으로 보이며 업그레이드를 쉽게하는 WP 코드를 변경하지 않아도됩니다.

해결책 3

http://www.warpconduit.net/2011/08/02/fix-redirection-and-error-page-on-empty-wordpress-search/

솔루션 2와 유사하지만 광범위하고 약간 다릅니다.

if(!is_admin()){
    add_action('init', 'search_query_fix');
    function search_query_fix(){
        if(isset($_GET['s']) && $_GET['s']==''){
            $_GET['s']=' ';
        }
    }
}

1
솔루션 2의 문제점은 실제로 게시물을 전혀 반환하지 않아야 할 때 모든 게시물 (또는 공백이있는 모든 게시물)을 반환한다는 것입니다.
— Felix Eve

2

Page Search.php를 생성하고이 코드를 붙여 넣고 "get_template_part ( 'loop', 'search');

                    <div id="container">
                        <div id="content" role="main">

            <?php if ( have_posts() ) : ?>
                            <h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'mb' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
                            <?php
                            /* Run the loop for the search to output the results.
                             * If you want to overload this in a child theme then include a file
                             * called loop-search.php and that will be used instead.
                             */
                             get_template_part( 'loop', 'search' );
                            ?>
            <?php else : ?>
                            <div id="post-0" class="post no-results not-found">
                                <h2 class="entry-title"><?php _e( 'Nothing Found', 'mb' ); ?></h2>
                                <div class="entry-content">
                                    <p><?php _e( 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.', 'twentyten' ); ?></p>
                                    <?php get_search_form(); ?>
                                </div><!-- .entry-content -->
                            </div><!-- #post-0 -->
            <?php endif; ?>
                        </div><!-- #content -->
                    </div><!-- #container -->

            <?php get_sidebar(); ?>
            <?php get_footer(); ?>

2

Tom의 솔루션 2를 기반으로하지만 게시물이 반환되지 않도록 확인하기 전에 이전과 같이 요청 필터를 추가하십시오.

add_filter( 'request', 'my_request_filter' );
function my_request_filter( $query_vars ) {
    if( isset( $_GET['s'] ) && empty( $_GET['s'] ) ) {
        $query_vars['s'] = " ";
        global $no_search_results;
        $no_search_results = TRUE;
    }
    return $query_vars;
}

그러나 이번에는 전역 변수를 설정하여 검색 결과를 반환해서는 안됩니다. 그런 다음 posts_where 후크를 사용하여 게시물이 반환되지 않도록하십시오.

add_filter( 'posts_where' , 'posts_where_statement' ); 
function posts_where_statement( $where ) {
    global $no_search_results;
    if($no_search_results) {
        $where .= ' AND 1=0';
    }
    return $where;
}

1

검색어가 비어 있는지 확인 ( get_search_query () ) 첫 번째 IF를 다음과 같이 바꾸십시오.

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

나는 이것이 충분한 해결책이라고 생각합니다. 간단하고 깨끗합니다. 코드를 복잡하게 할 수있는 특수 필터 및 동작이 없음
— Kamil

0

다음과 같이 테마에서 처리합니다. 이 코드를 사용해보십시오 :

<?php if (!have_posts()): ?>
    <article id="post-0">
        <header>
            <h3>No posts found.</h3>
        </header> <!-- end article header -->

        <section class="post_content">
           Sorry, we found 0 posts for your search, Please try searching again.
        </section> <!-- end article section -->

        <footer>
        </footer> <!-- end article footer -->

    </article> <!-- end article -->
<?php endif; ?>

우리는 if (! have_posts ()) 조건을 처리하고 있습니다. if (have_posts)가 시작되기 전에 h3.archive 제목 바로 뒤에 넣으십시오. 컨텐츠 영역에서 검색 양식 기능을 호출 할 수도 있습니다.


0

나는 또한 같은 문제에 직면했다. 기본적으로 wordpress에 의해 주어진다.

그러나 운 좋게 나는 나를 도운 무언가를 발견했다.

아래 "Functions.php"에 추가하십시오

 function SearchFilter($query) {
    // If 's' request variable is set but empty
    if (isset($_GET['s']) && empty($_GET['s']) && $query->is_main_query()){
        $query->is_search = true;
        $query->is_home = false;
    }
    return $query;}
add_filter('pre_get_posts','SearchFilter');

search.php에서 아래 줄 (15 번 줄)을 바꿉니다.

<?php if ( have_posts() && strlen( trim(get_search_query()) ) != 0 ) : ?>

그것도 당신을 도울 것입니다

자세한 내용은 다음을 읽으십시오 : 빈 검색 워드 프레스 사용자 정의


0

빈 검색을 피하는 한 가지 방법은 검색 필드의 빈 값에 대한 자바 스크립트 검사를 수행하고 발견 된 필드가 비어 있으면 다음과 같이 검색 양식 제출을 중지합니다.

$('#searchform').submit(function(){

            search_value =$.trim($('#searchform #s').val());

            if(search_value == ""){

                return false; // You can also pop a notification here to inform to user.
            }

});

0
# Catch empty searches
RewriteCond %{QUERY_STRING} ^s=$
RewriteRule ^ /? [L,R=301]

이것이 어떻게 질문에 대답하는지 확실하지 않습니다. 위 의 편집 버튼을 사용 하여 답변 을 편집 하고이 코드의 기능, 배치 위치 및 문제 해결 방법에 대한 세부 정보를 추가 할 수 있습니까?
— Howdy_McGee
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.