Untitled

mail@pastecode.io avatar
unknown
plain_text
9 days ago
2.4 kB
5
Indexable
Never


add_action('marketking_inside_tag_area', 'custom_product_tag_adder');

function custom_product_tag_adder() {
    $product_id = sanitize_text_field(marketking()->get_pagenr_query_var());

    // Display the form
    ?>
    <div class="custom-tag-adder">
        <input type="text" id="new-tag-name" name="new-tag-name" placeholder="Enter new tag" style="margin-top:10px">
        <button id="add-new-tag" class="button btn btn-small">Add Tag</button>
    </div>

    <script type="text/javascript">
    jQuery(document).ready(function($) {
        $('#add-new-tag').on('click', function(e) {
            e.preventDefault();
            var tagName = $('#new-tag-name').val();
            if (tagName) {
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'add_product_tag',
                        product_id: <?php echo $product_id; ?>,
                        tag_name: tagName,
                        security: '<?php echo wp_create_nonce("add-product-tag-nonce"); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            alert('Error adding tag: ' + response.data);
                        }
                    }
                });
            }
        });
    });
    </script>
    <?php
}

add_action('wp_ajax_add_product_tag', 'add_product_tag_callback');

function add_product_tag_callback() {
    check_ajax_referer('add-product-tag-nonce', 'security');

    $product_id = intval($_POST['product_id']);
    $tag_name = sanitize_text_field($_POST['tag_name']);

    if (!current_user_can('edit_product', $product_id)) {
        wp_send_json_error('You do not have permission to edit this product.');
    }

    $term = wp_insert_term($tag_name, 'product_tag');

    if (is_wp_error($term)) {
        if ($term->get_error_code() === 'term_exists') {
            $term_id = get_term_by('name', $tag_name, 'product_tag')->term_id;
        } else {
            wp_send_json_error($term->get_error_message());
        }
    } else {
        $term_id = $term['term_id'];
    }

    wp_set_object_terms($product_id, $term_id, 'product_tag', true);

    wp_send_json_success();
}
Leave a Comment