AJAX Wordpress. Code example open

AJAX Wordpress. Code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: WordPress 4.0+, PHP 5.6 +

In this example, we will create a button after pressing which AJAX technology will load your latest posts without reloading the page. Let’s get started!

Create a new ajax.js file and upload it to the assets/js/ajax.js directory. Сonnect this script to our theme through the function.php file:


<?php 

function mytheme_enqueue_ajax() {

wp_enqueue_script('mythemename-ajax', get_template_directory_uri() . 'assets/js/ajax.js', array('jquery'), '1.0', true);

}

add_action('wp_enqueue_scripts', 'mytheme_enqueue_ajax'); // Standard hook for connecting scripts

?>

2. It is impossible to translate the text into javascript and for this we will write a function in PHP that will translate our text into JavaScript. We will also add this supplemented code to ours function.php file:


<?php 


function mytheme_enqueue_ajax() {

wp_enqueue_script('mythemename_ajax', get_template_directory_uri() . 'assets/js/ajax.js', array('jquery'), '1.0', true);

// Write the function of translation of the javascript string
wp_localize_script(
    'mythemename_ajax', // id of the ajax.js connection function
    'mythemename_ajax_localize', 
    array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('ajax-nonce'), // WordPress nonce for security
        'string' => esc_html__('Hello', 'my-theme-textdomain'), // Translation of the first term
        'string2' => esc_html__('World', 'my-theme-textdomain') // The translation of the second term, you can add even more
         )
	);
 
};
 
add_action('wp_enqueue_scripts', 'mytheme_enqueue_ajax');

?>

3. Now let’s write our jax function in the file assets/js/ajax.js


<script>
jQuery(document).ready(function ($) {
$('#post_button').on('click',function(e){
e.preventDefault; 
$.ajax({
    url:mythemename_ajax_localize.ajaxurl,
    data: {
        'action' : 'mytheme_ajax_example', // function that will output posts
        'nonce' : mythemename_ajax_localize.nonce, // get wp nonce
        'string_one' : mythemename_ajax_localize.string, // Translation 1
        'string_two' : mythemename_ajax_localize.string2, // Translation 2
    },
    succes: function(data) {
        $('#content_block').append(data); // div id where the content will be displayed
    },
    error: function(errorThrown) {
        alert(errorThrown); // error alert
    };
}); 
} );
});
</script>

4. Let’s create a function for outputting posts mytheme_ajax_example(). Add in function.php code below:


<?php 

function mytheme_ajax_example() {
    if(!wp_verify_nonce($_REQUEST['nonce'], 'ajax-nonce')) {
        die; // if not verify nonce stop function
    }
    if(isset($_REQUEST['string'])) {
        echo $_REQUEST['string']; // Here is our first translation
    }

    if(isset($_REQUEST['string2'])) {
        echo $_REQUEST['string2']; Here is our second translation
    }

// Let's create a new WP_Query to display posts
   $posts_per_page = '-1';
    $new_query = new WP_Query("posts_per_page=$posts_per_page&orderby=comment_count");
    if ($new_query->have_posts()):

        while ($new_query->have_posts()): $new_query->the_post();

            echo $post->ID;

        endwhile;
    endif;

        wp_reset_postdata();

    die;
}

add_action('wp_ajax_mytheme_ajax_example', 'mytheme_ajax_example');
add_action('wp_ajax_nopriv_mytheme_ajax_example', 'mytheme_ajax_example'); //ajax for not logged users

?>

4. Now in the template we will add our div which is registered in a script


<button id="post_button">Show all posts</button>
<div id="#content_block"></div> 

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation