Untitled

mail@pastecode.io avatar
unknown
plain_text
22 days ago
1.7 kB
1
Indexable
Never
function custom_dashboard_add_tag() {
    $new_tag = isset($_POST['new_tag']) ? sanitize_text_field($_POST['new_tag']) : '';
    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;

    if ($new_tag && $post_id) {
        $term = wp_insert_term($new_tag, 'product_tag');
        if (!is_wp_error($term)) {
            wp_set_post_terms($post_id, [$term['term_id']], 'product_tag', true);
            wp_send_json_success();
        } else {
            wp_send_json_error($term->get_error_message());
        }
    }
    wp_die();
}
add_action('wp_ajax_custom_dashboard_add_tag', 'custom_dashboard_add_tag');
add_action('wp_ajax_nopriv_custom_dashboard_add_tag', 'custom_dashboard_add_tag');
function custom_tag_area() {
    ?>
    <div id="custom-tag-area">
        <input type="text" id="custom-tag-input" style="margin-top:25px;" placeholder="Add new tag" />
        <button id="custom-tag-button">Add</button>
    </div>
    <?php
}
add_action('marketking_inside_tag_area', 'custom_tag_area');
add_action('marketking_dashboard_head', function(){
	?>
	<script>
		jQuery(document).ready(function($) {
		    $('#custom-tag-button').on('click', function() {
		        var newTag = $('#custom-tag-input').val();
		        var postId = $('#post_ID').val();

		        if (newTag) {

    	    		var datavar = {
    		            action: 'custom_dashboard_add_tag',
    		            new_tag: newTag,
	                    post_id: postId,
    		        };


    		        $.post(marketking_display_settings.ajaxurl, datavar, function(response){
    		        	setTimeout(function(){
    		        		location.reload();
    		        	}, 250);
    		        });

		        }
		    });
		});

	</script>
	<?php
});
Leave a Comment