• alirezan137

    (@alirezan137)


    I wrote a code that adds two taxonomies to the WordPress product and the table function with the short code [display_all_products] you can display the products as a table list I added a code to filter and update the values of the table in the form of Ajax But the filtering part is not working. Please guide me where the problem is or write me the correct code. I will be grateful

    <?php
    function create_product_brand()
    {
        register_taxonomy(
            'car_product_brand',
            'product',
            array(
                "label" => "Product Brand",
                'rewrite' => array('slug' => 'products_brand'),
                'show_admin_column' => true,
                'hierarchical' => true
            )
        );
    }
    add_action('init', 'create_product_brand', 0);
    
    function create_technical_characteristics()
    {
        register_taxonomy(
            'technical_characteristics',
            'product',
            array(
                "label" => "Technical Characteristics",
                'rewrite' => array('slug' => 'technical_characteristics')
            )
        );
    }
    add_action('init', 'create_technical_characteristics', 0);
    
    
    function display_all_products_table()
    {
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1,
        );
    
        $query = new WP_Query($args);
    
        if ($query->have_posts()) {
    
            $output .= '<style>
            /* CSS for pagination and filters */
            .pagination {
                display: flex;
                justify-content: center;
                list-style-type: none;
                padding: 0;
            }
    
            .pagination li {
                margin: 0 5px;
                display:block;
                width:30px;
                text-align:center;
                background-color:#EBEBF5;
                border-radius: 5px;
            }
    
            .pagination li a {
                display:block;
                padding:2px;
                text-decoration: none;
                cursor: pointer;
                color:#000080;
                border-radius: 5px;
            }
    
            .pagination li.active a {
                font-weight: bold;
                background-color:#000080;
                color:white;
            }
    
            #dataTable thead tr{
                background-color: #000080 !important;
            }
    
            #dataTable th{
                color:white;
                text-align:center;
            }
    
            #dataTable td{
                color:black;
                text-align:center;
                border:none;
            }
    
            table tr:nth-child(even) {
                background-color: #FAFAFB; 
            }
    
            table tr:nth-child(odd) {
                background-color: #FFFFFF;
            }
    
            #filters {
                margin-bottom: 20px;
            }
    
            #filters select, #search {
                margin-right: 10px;
            }
            </style>';
    
            $output .= '
                <script>
                document.addEventListener("DOMContentLoaded", function() {
                    var table = document.getElementById(\'dataTable\');
                    var rowsPerPage = 15;
                    var rows = table.rows.length - 1; 
                    var pageCount = Math.ceil(rows / rowsPerPage);
                    var currentPage = 1;
    
                    function showPage(page) {
                        var start = (page - 1) * rowsPerPage;
                        var end = start + rowsPerPage;
    
                        for (var i = 1; i <= rows; i++) {
                            if (i > start && i <= end) {
                                table.rows[i].style.display = \'table-row\';
                            } else {
                                table.rows[i].style.display = \'none\';
                            }
                        }
                    }
    
                    function setupPagination() {
                        var pagination = document.getElementById(\'pagination\');
                        var html = \'\';
    
                        for (var i = 1; i <= pageCount; i++) {
                            html += \'<li\' + (i === currentPage ? \' class="active"\' : \'\') + \'><a>\' + i + \'</a></li>\';
                        }
    
                        pagination.innerHTML = html;
    
                        var pageLinks = pagination.querySelectorAll(\'a\');
                        pageLinks.forEach(function(link, index) {
                            link.addEventListener(\'click\', function() {
                                currentPage = index + 1;
                                showPage(currentPage);
                                setupPagination();
                            });
                        });
                    }
    
                    showPage(1);
                    setupPagination();
                });
    
                jQuery(document).ready(function($) {
                    $("#filter_category, #filter_brand").change(function() {
                        var categoryValue = $("#filter_category").val();
                        var brandValue = $("#filter_brand").val();
    
                        $.ajax({
                            url: ajaxurl,
                            type: "POST",
                            data: {
                                action: "filter_products",
                                category: categoryValue,
                                brand: brandValue
                            },
                            success: function(data) {
                                $("#dataTable tbody").html(data);
                                showPage(1);
                                setupPagination();
                            }
                        });
                    });
                });
                </script>
                ';
    
            $output .= '<div id="filters">';
            $output .= '<select id="filter_category">';
            $output .= '<option value="">All Categories</option>';
    
            $categories = get_terms('product_cat');
            if (!empty($categories)) {
                foreach ($categories as $category) {
                    $output .= '<option value="' . $category->term_id . '">' . $category->name . '</option>';
                }
            }
            $output .= '</select>';
    
            $output .= '<select id="filter_brand">';
            $output .= '<option value="">All Brands</option>';
    
            $brands = get_terms('car_product_brand');
            if (!empty($brands)) {
                foreach ($brands as $brand) {
                    $output .= '<option value="' . $brand->term_id . '">' . $brand->name . '</option>';
                }
            }
            $output .= '</select>';
    
            $output .= '<input type="text" id="search" placeholder="Search...">';
    
            $output .= '<button id="filter_button">Filter</button>';
            $output .= '</div>';
    
            $output .= '<table id="dataTable">';
            $output .= '<thead>';
            $output .= '<tr>';
            $output .= '<th>Index</th>';
            $output .= '<th>Product ID</th>';
            $output .= '<th>Technical Characteristics</th>';
            $output .= '<th>Product Name</th>';
            $output .= '<th>Price</th>';
            $output .= '<th>Category</th>';
            $output .= '<th>Car Brand</th>';
            $output .= '</tr>';
            $output .= '</thead>';
            $output .= '<tbody>';
            $index = 1;
            while ($query->have_posts()) {
                $query->the_post();
                global $product;
    
                $product_id = $product->get_id();
                $product_title = $product->get_title();
                $product_price = $product->get_price_html();
    
                $categories = get_the_terms($product_id, 'product_cat');
                $category_links = array();
    
                if ($categories) {
                    foreach ($categories as $category) {
                        $category_links[] = '<a href="' . get_term_link($category) . '">' . $category->name . '</a>';
                    }
                }
    
                $brands = get_the_terms($product_id, 'car_product_brand');
                $product_brands = array();
    
                if ($brands) {
                    foreach ($brands as $brand) {
                        $product_brands[] = $brand->name;
                    }
                }
    
                $technical_characteristics = get_the_terms($product_id, 'technical_characteristics');
                $product_technical_characteristics = array();
    
                if ($technical_characteristics) {
                    foreach ($technical_characteristics as $characteristic) {
                        $product_technical_characteristics[] = $characteristic->name;
                    }
                }
    
                $output .= '<tr>';
                $output .= '<td>' . $index . '</td>';
                $output .= '<td>' . $product_id . '</td>';
                $output .= '<td>' . implode(', ', $product_technical_characteristics) . '</td>';
                $output .= '<td><a href="' . get_permalink($product_id) . '">' . $product_title . '</a></td>';
                $output .= '<td>' . $product_price . '</td>';
                $output .= '<td>' . implode(', ', $category_links) . '</td>';
                $output .= '<td>' . implode(', ', $product_brands) . '</td>';
                $output .= '</tr>';
    
                $index++;
            }
    
            $output .= '</tbody>';
            $output .= '</table>';
            $output .= '<ul class="pagination" id="pagination"></ul>';
    
            wp_reset_postdata();
            return $output;
        } else {
            return 'No products found.';
        }
    }
    
    add_action('wp_ajax_filter_products', 'filter_products');
    add_action('wp_ajax_nopriv_filter_products', 'filter_products');
    
    function filter_products()
    {
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => -1,
        );
    
        if (isset($_POST['category']) && $_POST['category'] != '') {
            $args['tax_query'][] = array(
                'taxonomy' => 'product_cat',
                'field' => 'id',
                'terms' => $_POST['category'],
            );
        }
    
        if (isset($_POST['brand']) && $_POST['brand'] != '') {
            $args['tax_query'][] = array(
                'taxonomy' => 'car_product_brand',
                'field' => 'id',
                'terms' => $_POST['brand'],
            );
        }
    
        if (isset($_POST['search']) && $_POST['search'] != '') {
            $args['s'] = $_POST['search'];
        }
    
        $query = new WP_Query($args);
    
        if ($query->have_posts()) {
            $index = 1;
            while ($query->have_posts()) {
                $query->the_post();
                global $product;
    
                $product_id = $product->get_id();
                $product_title = esc_html($product->get_title());
                $product_price = $product->get_price_html();
    
                $categories = get_the_terms($product_id, 'product_cat');
                $category_links = array();
                if ($categories) {
                    foreach ($categories as $category) {
                        $category_links[] = '<a href="' . esc_url(get_term_link($category)) . '">' . esc_html($category->name) . '</a>';
                    }
                }
    
                $brands = get_the_terms($product_id, 'car_product_brand');
                $product_brands = array();
                if ($brands) {
                    foreach ($brands as $brand) {
                        $product_brands[] = esc_html($brand->name);
                    }
                }
    
                $technical_characteristics = get_the_terms($product_id, 'technical_characteristics');
                $product_technical_characteristics = array();
                if ($technical_characteristics) {
                    foreach ($technical_characteristics as $characteristic) {
                        $product_technical_characteristics[] = esc_html($characteristic->name);
                    }
                }
    
                echo '<tr>';
                echo '<td>' . $index . '</td>';
                echo '<td>' . $product_id . '</td>';
                echo '<td>' . implode(', ', $product_technical_characteristics) . '</td>';
                echo '<td><a href="' . esc_url(get_permalink($product_id)) . '">' . $product_title . '</a></td>';
                echo '<td>' . $product_price . '</td>';
                echo '<td>' . implode(', ', $category_links) . '</td>';
                echo '<td>' . implode(', ', $product_brands) . '</td>';
                echo '</tr>';
    
                $index++;
            }
        } else {
            echo '<tr><td colspan="7">No products found.</td></tr>';
        }
    
        wp_die();
    }
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Try adding dataType : 'json', to your $.ajax() parameters. Same level as url: ajaxurl, etc. If the data is sent in jQuery’s default format, PHP cannot make sense of it and thus $_POST will have no usable data.

Viewing 1 replies (of 1 total)

The topic ‘problem wordpress code, filter not working’ is closed to new replies.