Custom Plugin: WordPress Frontend Edit Cannot Update

33 views Asked by At

I am making a custom plugin for my website. The purpose of this plugin is to add and edit posts from frontend. The add post is working fine, but the edit post doesn't work at all. When I update a post, nothing happen.

Please help. This is my code:

function enqueue_user_posts_script() {
    wp_enqueue_script('user-posts-script', plugin_dir_url(__FILE__) . 'user-posts.js', array('jquery'), '1.0', true);
    wp_localize_script('user-posts-script', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php'), 'edit_post_nonce' => wp_create_nonce('edit_post_nonce')));
}

add_action('wp_enqueue_scripts', 'enqueue_user_posts_script');



function display_frontend_edit_post_form() {
    // Pastikan pengguna masuk
    if (!is_user_logged_in()) {
        echo 'You must be logged in to edit posts.';
        return;
    }

    // Periksa apakah ada parameter post_id dalam URL
    if (!isset($_GET['post_id']) || empty($_GET['post_id'])) {
        echo 'Invalid request.';
        return;
    }

    $post_id = intval($_GET['post_id']);

    
    $current_user = wp_get_current_user();
    $post = get_post($post_id);
    if ($post->post_author != $current_user->ID) {
        echo 'You do not have permission to edit this post.';
        return;
    }

    
    ob_start(); ?>

    <form id="frontend-edit-post-form" method="post" enctype="multipart/form-data">
        <label for="post_title">Title:</label><br>
        <input type="text" id="post_title" name="post_title" value="<?php echo esc_attr($post->post_title); ?>" required><br>
        <label for="post_content">Content:</label><br>
        <?php wp_editor($post->post_content, 'post_content', array('textarea_name' => 'post_content')); ?><br>
        <input type="hidden" name="post_id" value="<?php echo $post_id; ?>">
        <input type="submit" name="submit_post" id="submit_post" value="Submit">
        <?php wp_nonce_field('frontend_edit_post_nonce', 'frontend_edit_post_nonce_field'); ?>
        <input type="hidden" name="action" value="handle_frontend_edit_post_submission">
    </form>

    <?php
    return ob_get_clean();
}



add_shortcode('frontend_edit_post_form', 'display_frontend_edit_post_form');


function handle_frontend_edit_post_submission() {
    // Periksa apakah nonce telah disertakan dan valid
    if (!isset($_POST['frontend_edit_post_nonce_field']) || !wp_verify_nonce($_POST['frontend_edit_post_nonce_field'], 'frontend_edit_post_nonce')) {
        error_log('Nonce verification failed.'); // Tambahkan ini untuk pesan debugging
        echo 'Security check failed.';
        wp_die();
    }

    $post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;

    // Periksa apakah pengguna adalah penulis postingan
    $current_user = wp_get_current_user();
    $post = get_post($post_id);
    if ($post->post_author != $current_user->ID) {
        error_log('User is not the author of the post.'); 
        echo 'You do not have permission to edit this post.';
        wp_die();
    }

   
    $post_title = isset($_POST['post_title']) ? sanitize_text_field($_POST['post_title']) : '';
    $post_content = isset($_POST['post_content']) ? wp_kses_post($_POST['post_content']) : '';

  
    $updated_post = array(
        'ID'            => $post_id,
        'post_title'    => $post_title,
        'post_content'  => $post_content,
    );

    
    $post_updated = wp_update_post($updated_post);

    
    if ($post_updated) {
        echo 'success'; // Berikan respons yang sesuai
    } else {
        echo 'error'; // Berikan respons yang sesuai
    }

    
    wp_die();
}

add_action('wp_ajax_handle_frontend_edit_post_submission', 'handle_frontend_edit_post_submission');
add_action('wp_ajax_nopriv_handle_frontend_edit_post_submission', 'handle_frontend_edit_post_submission');

and this is user-posts.js

jQuery(document).ready(function($) {
    $('.delete-post').on('click', function() {
        var post_id = $(this).data('postid');
        var confirmation = confirm('Are you sure you want to delete this post?');
        if (confirmation) {
            $.ajax({
                type: 'GET',
                url: ajax_object.ajax_url,
                data: {
                    'action': 'delete_user_post',
                    'post_id': post_id,
                    'nonce': ajax_object.edit_post_nonce
                },
                success: function(response) {
                    $('#post-message').html(response);
                }
            });
        }
    });

    // Menangani pengiriman formulir pembaruan posting
    $('#frontend-edit-post-form').on('submit', function(e) {
        e.preventDefault();

        var formData = new FormData(this);
        formData.append('action', 'handle_frontend_edit_post_submission');
        formData.append('frontend_edit_post_nonce_field', $('#frontend_edit_post_nonce_field').val()); // Menggunakan nonce frontend_edit_post_nonce_field di sini

        $.ajax({
            type: 'POST',
            url: '<?php echo admin_url('admin-ajax.php'); ?>',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                console.log('Response from server:', response); // Tambahkan ini untuk melihat respons dari server di console
                $('#post-message').html(response);
            }
        });
    });;
});

I need to make the edit post code works.

0

There are 0 answers