簡體   English   中英

限制 Wordpress 搜索到特定的博客類別不起作用

[英]Limiting Wordpress Search to specific blog category not working

所以我試圖在博客頁面上創建一個搜索表單,以便它只搜索類別為“博客”的帖子這是我正在使用的搜索表單代碼:

<form  method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">

                   <input type="hidden"  name="cat" id="blog" value="7" />
                   
                    <input type="text" value="<?php echo get_search_query(); ?>" name="s" />
                    <input type="submit" value="Search" />
            </form> 

這是搜索php代碼:

<?php
/**
 * The template for displaying search results pages
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result
 *
 * @package Scrap
 */

get_header();
?>

    <main id="primary" class="site-main">

        <?php
$s=get_search_query();
$args = array(
                's' =>$s
            );
    // The Query
$the_query = new WP_Query( $args );

if ( $the_query->have_posts() ) {
        _e("<h2 style='font-weight:bold;color:#000'>Search Results for: ".get_query_var('s')."</h2>");
        while ( $the_query->have_posts() ) {
           $the_query->the_post();
                 ?>
                    <li>
                        <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                    </li>
                 <?php
        }
    }else{
?>
        <h2 style='font-weight:bold;color:#000'>Nothing Found</h2>
        <div class="alert alert-info">
          <p>Sorry, but nothing matched your search criteria. Please try again with some different keywords.</p>
        </div>
<?php } ?>

    </main><!-- #main -->

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

搜索查詢時,url 加載就像它僅限於類別: https://www.scraperapi.com/?cat=7&s=proxies但它仍然顯示來自類別之外的頁面,它沒有加載與搜索查詢匹配的所有博客文章。 搜索表單位於https://www.scraperapi.com/blog/但它是 display:hidden 在頂部名為“blog-search”的 div 中。

非常感謝您提供的任何幫助!!

嘗試使用get_query_var獲取 query_variable “cat”,並將 cat 變量也包含在 WP_Query 中。 這里也有一些很好的信息。 目前 $args 僅包含帶有變量 $s 的搜索詞。 這是改編的 $args。

$cat = get_query_var('cat');
$s=get_search_query();
$args = array(
            's' => $s,
            'cat' => $cat
        );
//etc..

或者,也可以修改 $wp_query 全局變量。 這可以通過設置 $wp_query 的 tax_query 來完成。

global $wp_quey;
$tax_query[] = array(
array(
    'taxonomy' => 'cat',
    'field'    => 'id',
    'terms'    => $cat,
  )
);
$wp_query->set( 'tax_query', $tax_query );

您可以通過pre_get_posts鈎子過濾器攔截和修改查詢。

<?php

//function.php
add_filter( 'pre_get_posts', 'wpso_70266736' );
if ( ! function_exists( 'wpso_70266736' ) ) {
    function wpso_70266736( $query ) {
        if( $query->is_search() && $query->is_main_query() && !isset( $_GET['category'] ) ) {
            $query->set_404();
            status_header( 404 );
            get_template_part( 404 );
            exit();
        };
    };
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM