Đặt vấn đề
Trong trang web của chúng ta có blog và product. Yêu cầu là khi tìm kiếm trong blog thì chỉ xuất hiện bài viết trong mục blog và giao diện khác với trang hiển thị kết quả tìm kiếm của product.
Giải quyết vấn đề.
Để tạo được 2 trang tìm kiếm có giao diện khác nhau tùy vào custom post type ta sẽ tạo thêm 1 file php cho custom post type nhé.
1. Thêm function
Thêm đoạn code sau vào file functions.php. 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!^^
- Bình luận