Lọc sản phẩm theo từ khoá (tag) trong WooCommerce wp-admin

Trong 1 bài viết trước tôi có chia sẽ cách để , trong bài viết này sẽ lọc sản phẩm theo từ khoá hay theo tag trong phần quản lý sản phẩm WooCommerce.

Cũng như bài viết trước, để thêm tính năng filter sản phẩm theo tag thì bạn cần thêm đoạn code phía dưới vào file functions.php (Những ai chưa biết file functions.php ở đâu thì có thể xem tại đây)

// Add the dropdown list of tags
add_action('restrict_manage_posts', 'vutruso_woocommerce_filter_products_by_tag');
function vutruso_woocommerce_filter_products_by_tag() {
    global $typenow;
    if ($typenow == 'product') {
        $taxonomy = 'product_tag';
        $current_tag = isset($_GET[$taxonomy]) ? $_GET[$taxonomy] : '';
        $terms = get_terms($taxonomy);
        echo "<select name='$taxonomy' id='$taxonomy' class='postform'>";
        echo "<option value=''>All Tags</option>";
        foreach ($terms as $term) {
            $selected = ($term->slug == $current_tag) ? 'selected' : '';
            echo "<option value='$term->slug' $selected>$term->name</option>";
        }
        echo "</select>";
    }
}

// Modify the product query based on the selected tag
add_filter('parse_query', 'vutruso_woocommerce_filter_products_by_tag_query');
function vutruso_woocommerce_filter_products_by_tag_query($query) {
    global $pagenow, $typenow;
    if ($pagenow == 'edit.php' && $typenow == 'product' && isset($_GET['product_tag']) && $_GET['product_tag'] != '') {
        $query->query_vars['tax_query'][] = array(
            'taxonomy' => 'product_tag',
            'field' => 'slug',
            'terms' => $_GET['product_tag']
        );
    }
    return $query;
}

Sau khi thêm vào file functions.php bạn có thể lọc sản phẩm theo từ khoá (tag) như hình dưới (chọn tag) để xem sản phẩm nào nằm trong tag bạn vừa chọn là xong.

Chúc bạn thành công.

Nếu bạn thấy bài viết có ích hãy sao chép link và chia sẻ bài viết
daotiendung

Tiến Dũng Đào chuyên quản lý, vận hành các dịch vụ website. Anh có nhiều năm kinh nghiệm về VPS, Hosting, technical SEO, CMS. Đặc biệt yêu thích WordPress với hơn 5 năm phát triển theme và plugin. Sở thích của anh là đọc, viết blog, đi du lịch, tập võ và chia sẻ các kiến thức cho mọi người.

Bài viết liên quan