Untitled
unknown
plain_text
a year ago
2.7 kB
28
Indexable
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-names" name="new-tag-names" placeholder="Enter new tags (comma-separated)" style="margin-top:10px">
<button id="add-new-tags" class="button btn btn-small">Add Tags</button>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#add-new-tags').on('click', function(e) {
e.preventDefault();
var tagNames = $('#new-tag-names').val();
if (tagNames) {
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'add_product_tags',
product_id: <?php echo $product_id; ?>,
tag_names: tagNames,
security: '<?php echo wp_create_nonce("add-product-tags-nonce"); ?>'
},
success: function(response) {
if (response.success) {
alert('Tags added successfully');
} else {
alert('Error adding tags: ' + response.data);
}
}
});
}
});
});
</script>
<?php
}
add_action('wp_ajax_add_product_tags', 'add_product_tags_callback');
function add_product_tags_callback() {
check_ajax_referer('add-product-tags-nonce', 'security');
$product_id = intval($_POST['product_id']);
$tag_names = sanitize_text_field($_POST['tag_names']);
if (!current_user_can('edit_product', $product_id)) {
wp_send_json_error('You do not have permission to edit this product.');
}
$tag_array = array_map('trim', explode(',', $tag_names));
$term_ids = array();
foreach ($tag_array as $tag_name) {
if (empty($tag_name)) continue;
$term = wp_insert_term($tag_name, 'product_tag');
if (is_wp_error($term)) {
if ($term->get_error_code() === 'term_exists') {
$term_ids[] = get_term_by('name', $tag_name, 'product_tag')->term_id;
} else {
wp_send_json_error($term->get_error_message());
}
} else {
$term_ids[] = $term['term_id'];
}
}
wp_set_object_terms($product_id, $term_ids, 'product_tag', true);
wp_send_json_success();
}Editor is loading...
Leave a Comment