Phần 1 tại đây
Thêm chức năng sắp xếp, tìm kiếm cho plugin wordpress phần 2
Short code yatch_detail để hiển thị chi tiết bài viết yatch trên một trang đã được tạo sẵn với shortcode [yatch_detail], bạn có thể làm như sau:
Trước tiên, hãy đảm bảo rằng bạn đã tạo một trang (page) trong WordPress và chèn shortcode [yatch_detail] vào nội dung của trang đó. Ví dụ, bạn có thể đặt tên trang là “Yatch Details”.
Cập nhật shortcode [yatch_detail] để nó có thể nhận biết và hiển thị chi tiết bài viết yatch dựa trên thông tin trong URL.
Dưới đây là cách bạn có thể chỉnh sửa class xử lý shortcode Yatch_Detail_Shortcode:
class Yatch_Detail_Shortcode { public function __construct() { add_shortcode('yatch_detail', array($this, 'display_yatch_detail')); } public function display_yatch_detail($atts) { global $post; // Lấy giá trị slug của yatch từ URL if (isset($_GET['yatch_slug'])) { $yatch_slug = sanitize_text_field($_GET['yatch_slug']); } else { return '<p>' . __('No yatch selected.', 'text-domain') . '</p>'; } // Tìm bài viết theo slug $yatch_post = get_posts(array( 'name' => $yatch_slug, 'post_type' => 'yatch_post', 'post_status' => 'publish', 'numberposts' => 1 )); if (!$yatch_post) { return '<p>' . __('Yatch not found.', 'text-domain') . '</p>'; } // Thiết lập dữ liệu post cho WordPress $post = $yatch_post[0]; setup_postdata($post); ob_start(); // Hiển thị chi tiết bài viết echo '<h1>' . get_the_title() . '</h1>'; echo '<div>' . get_the_content() . '</div>'; echo '<p>Star Rating: ' . esc_html(get_post_meta(get_the_ID(), '_yatch_star_rating', true)) . '</p>'; echo '<p>Review Count: ' . esc_html(get_post_meta(get_the_ID(), '_yatch_review_count', true)) . '</p>'; echo '<p>Price: $' . esc_html(get_post_meta(get_the_ID(), '_yatch_price', true)) . '</p>'; wp_reset_postdata(); return ob_get_clean(); } } // Khởi tạo class new Yatch_Detail_Shortcode();
Khi bạn tạo liên kết đến trang chứa shortcode [yatch_detail], bạn cần truyền slug của yatch qua URL. Ví dụ, nếu trang “Yatch Details” của bạn có URL là https://example.com/yatch-details, bạn có thể tạo liên kết như sau:
<a href="<?php echo esc_url(add_query_arg('yatch_slug', get_post_field('post_name', get_the_ID()), 'https://example.com/yatch-details')); ?>"> <?php the_title(); ?> </a>
Khi người dùng truy cập vào trang “Yatch Details” với URL chứa tham số yatch_slug, shortcode [yatch_detail] sẽ tự động nhận tham số này và hiển thị chi tiết bài viết tương ứng.
Ví dụ: https://example.com/yatch-details?yatch_slug=my-yatch
Kết quả là trang “Yatch Details” sẽ hiển thị thông tin chi tiết của bài viết yatch với slug là my-yatch.
Leave A Comment