Tùy chỉnh giao diện trang search cho mỗi custom post type khác nhau

clock 00:03

1. Thêm function

Thêm đoạn code sau vào file functions.php trong child theme. Thay search-product.php bằng tên file của bạn.


// Custom template search
function template_chooser($template) {
    global $wp_query;
    $post_type = get_query_var('post_type');
    if ( isset($_GET['s']) && $post_type == 'product' ) {
        return locate_template('search-product.php');
    }
    return $template;
}
add_filter('template_include', 'template_chooser');

2. Tạo giao diện

Như ví dụ trên thì ta sẽ tạo file có tên search-product.php để hiển thị kết quả cho post type là product. Còn trang blog mặc định kết quả hiển thị ở search.php rồi.

Giao diện thì bạn tùy chỉnh nha.

3. Tùy chỉnh form tìm kiếm

Thêm đoạn sau vào form tìm kiếm:


<input type="hidden" name="post_type" value="product" />

Code form tìm kiếm cho product:


<form method="get" class="searchform" action="<?php echo esc_url( home_url( '/' ) );?>">
    <input type="text" class="field s" name="s" value="" placeholder="Search entire store here..." />
    <input type="hidden" name="post_type" value="og_product" />
    <span class="icon_search"></span>
</form>

Code form tìm kiếm cho Blog:


<form method="get" class="searchform" action="<?php echo esc_url( home_url( '/' ) );?>">
    <input type="text" class="field s" name="s" value="" />
    <input type="hidden" name="post_type" value="post" />
    <input type="submit" value="Search" />
</form>

OK đã hoàn thành.

Chúc các bạn thành công!

Nguồn: levantoan.com