{"id":2511,"date":"2013-11-19T09:49:58","date_gmt":"2013-11-19T09:49:58","guid":{"rendered":"http:\/\/www.wordpressintegration.com\/blog\/?p=2511"},"modified":"2023-09-19T12:21:25","modified_gmt":"2023-09-19T12:21:25","slug":"wordpress-post-using-ajax","status":"publish","type":"post","link":"https:\/\/www.wordpressintegration.com\/blog\/wordpress-post-using-ajax\/","title":{"rendered":"A Complete Tutorial on Deleting a WordPress Post Using AJAX"},"content":{"rendered":"<p align=\"justify\"><a href=\"https:\/\/en.wikipedia.org\/wiki\/Ajax_(programming)\" target=\"_blank\" rel=\"noopener noreferrer\">AJAX<\/a>, which stands for <i>Asynchronous JavaScript and XML<\/i>, is a remarkable web technology that enables a web page to perform actions or updates dynamically without needing to reload it.<!--more--> A Website, that uses Ajax technology, is more interactive and responsive than a non-Ajax site. This technology not only helps developers make useful tools and better interfaces, but also lets them optimize code and minimize bandwidth usage.<\/p>\n<p align=\"justify\">As AJAX bridges the gap between client-side and server side code, it is being used by all types of web sites including WordPress. For instance, Google Docs and Google Maps utilize this technology to process the user\u2019s request without reloading the web page. However AJAX can be used freely anywhere, but WordPress has built-in support for it. In WordPress, it is used to perform instant updates that include comment moderation and adding or deleting items from lists such as posts, categories etc. In this tutorial, we\u2019ll show you how to delete a WordPress Post Using AJAX.<\/p>\n<p>Let\u2019s start by understanding AJAX flow.<\/p>\n<h2>The AJAX Flow:<\/h2>\n<p>To create something using AJAX, you\u2019ll require following things:<\/p>\n<ul>\n<li>An action to trigger the call<\/li>\n<li>An AJAX call<\/li>\n<li>Server side code which is executed<\/li>\n<li>JavaScript code to process the results<\/li>\n<\/ul>\n<p align=\"justify\">Though all the above listed things are not required all the time, but we\u2019ve shown you how it generally goes. Let\u2019s go ahead to know how AJAX can be useful in deleting a WordPress post.<\/p>\n<p align=\"justify\">If you\u2019ve a WordPress site that has a huge number of posts, you\u2019ll be able to delete posts from the front-end. To delete a post, you\u2019re required to click a link that uses a script to delete the post and redirects you back.<\/p>\n<p>Using AJAX, you can fade the post out without reloading entire page. In this deletion process:<\/p>\n<ul>\n<li>The trigger is the link which we&#8217;ll click to delete the post.<\/li>\n<li>An AJAX call will contain an identifier to know which post to delete and a security nonce.<\/li>\n<li>On the server side, the data passed by the AJAX call will be used to delete the post.<\/li>\n<li>On the front-end, the post will be faded out.<\/li>\n<\/ul>\n<h2>The Trigger:<\/h2>\n<p align=\"justify\">All you&#8217;ve to do is create a link, and then give it a class name that will be used to detect the click using JavaScript. Use the following snippet of code:<\/p>\n<p>&lt; pre class=&#8221;lang:default decode:true&#8221; &gt;<br \/>\n&lt; div <!--?php post_class() ? &gt;&gt;&lt;br ?--> &lt; .h1 &gt;&lt; a href=&#8221;&lt; ?php the_permalink() ?&gt;&#8221;&gt;&lt; ?php the_title() ?&gt;&lt; \\h1 &gt;<br \/>\n&lt; div class=&#8221;post-content&#8221; &gt;<br \/>\n&lt; ?php the_content() ? &gt;<br \/>\n&lt; \/div &gt;<br \/>\n&lt; ?php if( current_user_can( &#8216;delete_post&#8217; ) ) : ? &gt;<br \/>\n&lt; a href=&#8221;#&#8221; data-id=&#8221;<!--?php the_ID() ? &gt;\" data-nonce=\"&lt; ?php echo wp_create_nonce('my_delete_post_nonce') ? &gt;\" class=\"delete-post\"&gt;delete&lt; \/a &gt;&lt;br ?--> &lt; ?php endif ? &gt;<br \/>\n&lt; \/div &gt;<br \/>\n&lt; \/pre &gt;<\/p>\n<p align=\"justify\">Here, the <i>current_user_can()<\/i> parameter is used to check whether or not the current user has permissions to delete a post and only output the link when required. Additionally, the \u201cid\u201d has been added as a data attribute to the link which will be clicked by user to delete the post.<\/p>\n<p align=\"justify\">In many cases, you can also add \u201c<i>id<\/i>\u201d to the starting post div. This way there is no need to add it as a data attribute to all links, when you\u2019ve multiple control links. Instead, you can check the id of the common ancestor.<\/p>\n<p align=\"justify\">The \u201c<i>nonce<\/i>\u201d is added as the data-nonce parameter. When a user will click the link, the script will check the existence of \u201c<i>nonce<\/i>\u201d to ensure that the user who clicked on the link has the rights to delete the post. Later on, we\u2019ll add a real URL instead of \u201c#\u201d sign, so it can also work without using JavaScript.<\/p>\n<h2>The Call:<\/h2>\n<p align=\"justify\">In this step, an AJAX call will be performed through JavaScript to detect the link, and then it\u2019ll send data to the server for processing. Before writing the JavaScript code, we\u2019ll show you how to add JavaScript files to WordPress. Add the following code to the theme\u2019s functions.php file:<\/p>\n<p>&lt; pre class=&#8221;lang:default decode:true&#8221; &gt;<br \/>\nfunction my_frontend_script( ) {<br \/>\nwp_enqueue_script( &#8216;my_script&#8217;, get_template_directory_uri( ) .<br \/>\n&#8216;\/js\/my_script.js&#8217;, array( &#8216;jquery&#8217; ), &#8216;1.0.0&#8217;, true );<br \/>\n}<br \/>\nadd_action( &#8216;wp_enqueue_scripts&#8217;, &#8216;my_frontend_script&#8217; );<br \/>\n&lt; \/pre &gt;<\/p>\n<p align=\"justify\">In the above code, the <i>wp_enqueue_script()<\/i> is used to tell the WordPress that you\u2019ve added a script to the header of your theme. Keep in mind that you\u2019ll require to use the <i>admin_enqueue_scripts<\/i> hook for the WordPress backend.<\/p>\n<p align=\"justify\">In WordPress, all AJAX calls should be routed through the admin-ajax.php file that resides in wp-admin. In JavaScript, there\u2019s no way of doing this as everyone\u2019s WordPress has a different location. Fortunately, there is a method through which you can pass variables to your JavaScript functions by using the function <i>localize_script()<\/i>. Add the code given below into the <i>my_frontend_script()<\/i> function, after enqueuing your script:<\/p>\n<pre class=\"lang:default decode:true\">wp_localize_script( 'my_script', 'MyAjax', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ) ) );\r\n<\/pre>\n<p align=\"justify\">This function passes the \u201c<i>MyAjax<\/i>\u201d object to your script, so you can use the variables that it contains. Now you can write your JavaScript as shown below:<\/p>\n<pre class=\"lang:default decode:true\">jQuery( document ).ready( function($) {\r\n\t$(document).on( 'click', '.delete-post', function() {\r\n\t\tvar id = $(this).data('id');\r\n\t\tvar nonce = $(this).data('nonce');\r\n\t\tvar post = $(this).parents('.post:first');\r\n\t\t$.ajax({\r\n\t\t\ttype: 'post',\r\n\t\t\turl: MyAjax.ajaxurl,\r\n\t\t\tdata: {\r\n\t\t\t\taction: 'my_delete_post',\r\n\t\t\t\tnonce: nonce,\r\n\t\t\t\tid: id\r\n\t\t\t},\r\n\t\t\tsuccess: function( result ) {\r\n\t\t\t\tif( result == 'success' ) {\r\n\t\t\t\t\tpost.fadeOut( function(){\r\n\t\t\t\t\t\tpost.remove();\r\n\t\t\t\t\t});\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t})\r\n\t\treturn false;\r\n\t})\r\n})\r\n<\/pre>\n<p align=\"justify\">The above JavaScript code will detect whenever a user will click on the delete post link. Be sure to use the <i>return false<\/i> function at the end, so the link will not be followed. This script will remove the post ID, the security nonce and the post element from the HTML.<\/p>\n<p align=\"justify\">The parameter \u201c<i>action<\/i>\u201d must be passed in the above code, as the AJAX call will be performed by using the Ajax URL that we\u2019ll define and pass to the script. Also, we\u2019ll pass the nonce and id to the server-side script.<\/p>\n<p align=\"justify\">If the server returns \u201c<i>success<\/i>\u201d message to JavaScript, then the post will be faded out. Note that the success of an AJAX call doesn\u2019t depend on the success of the deletion process. The call will still be successful, even if the item is not deleted.<\/p>\n<h2>On The Server:<\/h2>\n<p align=\"justify\">Open the theme\u2019s function.php file once again, and add the following script by which the server will delete the post.<\/p>\n<pre class=\"lang:default decode:true\">add_action( 'wp_ajax_my_delete_post', 'my_delete_post' );\r\nfunction my_delete_post(){\r\n\r\n\t$permission = check_ajax_referer( 'my_delete_post_nonce', 'nonce', false );\r\n\tif( $permission == false ) {\r\n\t\techo 'error';\r\n\t}\r\n\telse {\r\n\t\twp_delete_post( $_REQUEST['id'] );\r\n\t\techo 'success';\r\n\t}\r\n\r\n\tdie();\r\n}\r\n<\/pre>\n<p align=\"justify\">As Hooks are created dynamically according to the action, the prefix wp_ajax_ we\u2019ve used before the action will figure out the name of your hook. You can also prefix your action with <i>wp_ajax_nopriv_<\/i>, if you want to allow non-logged in users to execute something.<\/p>\n<p align=\"justify\">After the function is created, a security nonce is used. The <i>check_ajax_referer()<\/i> will use the name of the action, the parameter name in which it is passed and an argument to make the script die on failure.<\/p>\n<p align=\"justify\">When we perform deletion, then it\u2019ll either return \u201c<i>success<\/i>\u201d or \u201c<i>error<\/i>\u201d. If it returns \u201c<i>success<\/i>\u201d, it means the user has permission to delete the post. In that case, it will be detected by our JavaScript and the post will be removed from the DOM.<\/p>\n<p align=\"justify\">If it returns \u201c<i>error<\/i>\u201d, when the user doesn\u2019t have permission to delete the post, nothing will happen.<\/p>\n<h2>Graceful Degradation:<\/h2>\n<p align=\"justify\">The most interesting thing about the AJAX workflow is that you need to do nothing additional to make it work without JavaScript. As AJAX calls pass POST or GET parameters, so all you need to do pass parameters via actual link. So modify your code for the post by adding the actual URL instead of \u201c#\u201d sign.<\/p>\n<p>&lt; pre class=&#8221;lang:default decode:true&#8221; &gt;<br \/>\n&lt; div <!--?php post_class() ? &gt;&gt;&lt;br ?--> &lt; .h1 &gt;&lt; a href=&#8221;<!--?php the_permalink() ?-->&#8220;&gt;<!--?php the_title() ?-->&lt; \\h1 &gt;<br \/>\n&lt; div class=&#8221;post-content&#8221; &gt;<br \/>\n&lt; ?php the_content() ? &gt;<br \/>\n&lt; \/div &gt;<\/p>\n<p>&lt; ?php if( current_user_can( &#8216;delete_post&#8217; ) ) : ? &gt;<br \/>\n&lt; ?php $nonce = wp_create_nonce(&#8216;my_delete_post_nonce&#8217;) ? &gt;<br \/>\n&lt; a href=&#8221;<!--?php echo admin_url( 'admin-ajax.php?action=my_delete_post&amp;id=' . get_the_ID() . '&amp;nonce=' . $nonce ) ? &gt;\" data-id=\"&lt;?php the_ID() ? &gt;\" data-nonce=\"&lt; ?php echo $nonce ? &gt;\" class=\"delete-post\" &gt;delete&lt; \/a&gt;&lt;br ?--> &lt; ?php endif ? &gt;<br \/>\n&lt; \/div &gt;<br \/>\n&lt; \/pre &gt;<\/p>\n<p align=\"justify\">Here, no major changes are made and the same nonce, action and ID are used as before. The only difference is that we\u2019ve used $_GET variables in place of $_POST. Internally, The &lt; i &gt;check_ajax_referer()&lt; \/i &gt; uses the $_REQUEST. As we\u2019ve already used it in the &lt; i &gt;wp_delete_post&lt; \/i &gt; function, there are no chances of any type of problem.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>AJAX, which stands for Asynchronous JavaScript and XML, is a remarkable web technology that enables a web page to perform actions or updates&#8230;<\/p>\n","protected":false},"author":14,"featured_media":2515,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[22],"tags":[599,25,598,600,496],"acf":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.wordpressintegration.com\/blog\/wp-json\/wp\/v2\/posts\/2511"}],"collection":[{"href":"https:\/\/www.wordpressintegration.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wordpressintegration.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wordpressintegration.com\/blog\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wordpressintegration.com\/blog\/wp-json\/wp\/v2\/comments?post=2511"}],"version-history":[{"count":3,"href":"https:\/\/www.wordpressintegration.com\/blog\/wp-json\/wp\/v2\/posts\/2511\/revisions"}],"predecessor-version":[{"id":5721,"href":"https:\/\/www.wordpressintegration.com\/blog\/wp-json\/wp\/v2\/posts\/2511\/revisions\/5721"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wordpressintegration.com\/blog\/wp-json\/wp\/v2\/media\/2515"}],"wp:attachment":[{"href":"https:\/\/www.wordpressintegration.com\/blog\/wp-json\/wp\/v2\/media?parent=2511"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wordpressintegration.com\/blog\/wp-json\/wp\/v2\/categories?post=2511"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wordpressintegration.com\/blog\/wp-json\/wp\/v2\/tags?post=2511"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}