• I have a simple site with just a button, and also I’m developing a plugin, what I want to do is that when I click that button the plugin will create a post. But so far, I’ve been having trouble connecting them both.

    I’ve tried something like this with a custom HTML block:

    <button id="create-post-button">Create New Post</button>
    
    <script>
    jQuery(document).ready(function($) {
        $('#create-post-button').click(function() {
            $.ajax({
                url: '<?php echo admin_url('admin-ajax.php'); ?>',
                type: 'POST',
                data: {
                    action: 'createPost'
                },
                success: function(response) {
                    alert(response);
                }
            });
        });
    });
    </script>

    And my plugin php file looks like this:

    <?php
    /*
     * Plugin Name: ReachDog WordPress Plugin
     * Description: Test Plugin for ReachDog in WordPress
     */
    
    
    defined ('ABSPATH') OR die("You shouldn't be here!");
    
    class ReachDogPlugin {
    	function __construct(){
    		add_action('wp_ajax_createPost', 'createPost');
    		add_action('wp_ajax_nopriv_createPost', 'createPost');
    	}
    	
    	function createPost(){
    		// Set the post data
    		$new_post = array(
    			'post_title' => 'ReachDog Post Title 1.2',
    			'post_content' => 'One day this is going to be an actual nice plugin, for now this is all you get, Junior quality kind of code.',
    			'post_status' => 'publish',
    			'post_author' => 1, // The ID of the user who is creating the post
    			'post_category' => array(2, 3) // An array of category IDs to assign to the post
    		);
    
    		// Insert the post into the database
    		$new_post_id = wp_insert_post($new_post);
    
    		// Check if the post was successfully inserted
    		if ($new_post_id) {
    			echo "New post created with ID: " . $new_post_id;
    		} else {
    			echo "Error creating new post.";
    		}
    
    		wp_die();
    	}
    }
    
    if(class_exists('ReachDogPlugin')){
    	$reachDogPlugin = new ReachDogPlugin('ReachDod Plugin Initialized!');	
    }

    But still, when I click the button nothing happens, I’m not sure what I’m doing wrong to connect the button to my plugin.

Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator Jose Castaneda

    (@jcastaneda)

    THEME COFFEE MONKEY

    Hi there,

    From a quick look it could very well be in the way you’re calling the action hooks. Since you are using a class you would need to change that up to something like:

    add_action('wp_ajax_createPost', array( $this, 'createPost' ) );

    Let us know if that helps

    Moderator bcworkz

    (@bcworkz)

    100% what Jose said. One other thing, include dataType : 'json', in your .ajax() parameters or else your “action:” value will not be properly assigned to PHP’s $_REQUEST.

    I see you use the _no_priv_ action hook variant, allowing non-logged in users to create new posts. Consider carefully if this is what you want. You will likely get a lot of spam posts if some additional vetting is not performed. Also, non-logged in users would not have a specific user ID to be assigned as post author. You’d need a generic “anonymous” user ID to use if you allow non-logged in post creation.

    Thread Starter jfjaramillo

    (@jfjaramillo)

    I just tried both of you guys recommendations and still isn’t working. Is it neccesary to create an api endpoint so the front can access to that function?

    @jcastaneda @bcworkz

    Moderator bcworkz

    (@bcworkz)

    An Ajax call doesn’t typically use the API. While an Ajax call could access the API, it’s not typical and not otherwise required.

    I tested your code on my site. After making the corrections Jose and I suggested, it does work on my site. Whatever issue you still have, it’s external to the code you’ve posted.

    Do you have jQuery enqueued and loaded for this page? It is necessary.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘How to add a function from a plugin to a button?’ is closed to new replies.