How to add a function from a plugin to a button?
-
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)
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.