$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>themes - Wordpress ajax insert and delete if already inserted delete the post id stored in custom table|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

themes - Wordpress ajax insert and delete if already inserted delete the post id stored in custom table

matteradmin9PV0评论

I am creating a wordpress ajax system to insert a post id. If the same post id was selected by logged in user then it wants to delete the particular id. For that i am creating a table like below it works.

function compare_new_table(){
            global $wpdb;
            global $compare_db_version;
            $compare_table = $wpdb->prefix . 'compare_post';
            $sql = "CREATE TABLE $compare_table (
                `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
                `user_id` int(11) unsigned NOT NULL DEFAULT '0',
                `post_id` int(11) unsigned NOT NULL DEFAULT '0',
                `post_type` varchar(20) NOT NULL,
                PRIMARY KEY (`id`),
                KEY `user_id` (`user_id`),
                KEY `post_id` (`post_id`)
                )";

             require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
             dbDelta( $sql );
            add_option( 'compare_db_version', $compare_db_version );
}
add_action('after_setup_theme', 'compare_new_table');

For enqueing script i am using lile below.

// Loads frontend scripts and styles
function sha_compare_enque_script()
{
wp_enqueue_script( 'com-compare-scripts', get_stylesheet_directory_uri() . '/inc/compare/js/compare.js', array( 'jquery' ), '0.6', false );
wp_localize_script( 'com-compare-scripts', 'com', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'com_nonce' ),
'errorMessage' => __( 'Something went wrong', 'com' )
) );   
}      
add_action( 'wp_enqueue_scripts', 'sha_compare_enque_script' );

After that started ajax and php code

    add_shortcode( 'compare-post-btn', array($this, 'compare_button_shortcode') );           
    add_action( 'wp_ajax_com_action', array($this, 'compare_post_shortcode') );


    function link_button_compare( $post_id ) {

    if ( !is_user_logged_in() ) {
        return;
    }

    $status = $this->get_post_status( $post_id, get_current_user_id() );
    ?>

    <a class="wpf-compare-link" href="#" data-id="<?php echo $post_id; ?>">
        <?php if ( $status ) { ?>
        <div class="wpf-compare"><i class="fa fa-heart"></i><span class="compare-text"><?php _e( 'uncompare', 'com' ); ?><span></div>
        <?php } else { ?>
                    <div class="wpf-not-compare"><i class="fa fa-heart"></i> <span class="fav-text"><?php _e( 'compare', 'com' ); ?></span></div>
        <?php } ?>
    </a>

    <?php
}


    function compare_post() {
    check_ajax_referer( 'com_nonce', 'nonce' );

    // bail out if not logged in
    if ( !is_user_logged_in() ) {
        wp_send_json_error();
    }

    // so, the user is logged in huh? proceed on
    $post_id = isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0;
    $user_id = get_current_user_id();

    if ( !$this->get_post_status( $post_id, $user_id ) ) {

        $this->insert_compare( $post_id, $user_id );

        wp_send_json_success( '<div class="com-compsre"><span class="compare-text">Uncompare<span></div>');
    } else {

        $this->delete_compare( $post_id, $user_id );

        wp_send_json_success( '<div class="com-not-compare"><span class="compare-text">Compare</span></div>');
    }
}


function get_post_status( $post_id, $user_id ) {
    $sql = "SELECT post_id FROM {$this->table} WHERE post_id = %d AND user_id = %d";

    return $this->db->get_row( $this->db->prepare( $sql, $post_id, $user_id ) );
}


public function insert_compare( $post_id, $user_id ) {
    $post_type = get_post_field( 'post_type', $post_id );

    return $this->db->insert(
        $this->table,
        array(
            'post_id' => $post_id,
            'post_type' => $post_type,
            'user_id' => $user_id,
        ),
        array(
            '%d',
            '%s',
            '%d'
        )
    );
}

public function delete_compare( $post_id, $user_id ) {
    $query = "DELETE FROM {$this->table} WHERE post_id = %d AND user_id = %d";

    return $this->db->query( $this->db->prepare( $query, $post_id, $user_id ) );
}


function get_compare( $post_type = 'all', $user_id = 0, $count = 10, $offset = 0 ) {
    $where = 'WHERE user_id = ';
    $where .= $user_id ? $user_id : get_current_user_id();
    $where .= $post_type == 'all' ? '' : " AND post_type = '$post_type'";


    $sql = "SELECT post_id, post_type
            FROM {$this->table}
            $where
            GROUP BY post_id
            ORDER BY post_type
            LIMIT $offset, $count";

    $result = $this->db->get_results( $sql );

    return $result;
}

function link_button_compare( $post_id ) {

    if ( !is_user_logged_in() ) {
        return;
    }

    $status = $this->get_post_status( $post_id, get_current_user_id() );
    ?>

    <a class="wpf-compare-link" href="#" data-id="<?php echo $post_id; ?>">
        <?php if ( $status ) { ?>
        <div class="wpf-compare"><i class="fa fa-heart"></i><span class="compare-text"><?php _e( 'uncompare', 'com' ); ?><span></div>
        <?php } else { ?>
                    <div class="wpf-not-compare"><i class="fa fa-heart"></i> <span class="fav-text"><?php _e( 'compare', 'com' ); ?></span></div>
        <?php } ?>
    </a>

    <?php
}

js file for this ajax

jQuery(function($) {

    $('a-compare-link').on('click', function(event) {
        event.preventDefault();

        var $self = $(this);

        var data = {
            post_id: $self.data('id'),
            nonce: com.nonce,
            action: 'com_action'
        };

        $self.addClass('com-compare-loading');

        $.post(com.ajaxurl, data, function(res) {

            if (res.success) {
                $self.html(res.data);

            } else {
                alert(com.errorMessage);
            }

            // remove loader
            $self.removeClass('com-compare-loading');
        });
    });


    $('a-not-compare').on('click', function(event) {
        event.preventDefault();

        var $self = $(this);

        var data = {
            post_id: $self.data('id'),
            nonce: com.nonce,
            action: 'com_action'
        };

        $self.addClass('com-compare-loading');

        $.post(com.ajaxurl, data, function(res) {

            if (res.success) {
                window.location.reload();

            } else {
                alert(com.errorMessage);
            }

            // remove loader
            $self.removeClass('com-compare-loading');
        });
    });

$('a-compare-link').click(function(){
  $('#comparebutton').show();
}); 

}); 
Post a comment

comment list (0)

  1. No comments so far