0

In general, I try to apply a "load more post" functionality to a loop, but I am failing to fire a PHP function within a plugin.

The PHP function is supposed to fire using a custom jQuery action with value "load_more". I use he following add_action functions to fire the PHP function:

add_action( 'wp_ajax_load_more', 'load_more_ajax_handler' );
add_action( 'wp_ajax_nopriv_load_more', 'load_more_ajax_handler' ); 

Within the jQuery script, I am able to console out following value:

{action: "load_more", query: "{"posts_per_page":3,"post_type":"artikler","paged"…_page":"50","no_found_rows":false,"order":"DESC"}", max: "4", page: "1", results: "10"}

I have never been able to fire the PHP function using the wp_ajax add_action method and according to documentation, I do not see what I am missing.

I initialize the jQuery script using following PHP function:

add_action( 'wp_enqueue_scripts', 'wordpress_my_load_more_scripts' );

function wordpress_my_load_more_scripts() 
{
    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

    $query_args = array(
        'posts_per_page'    => 3,
        'post_type'         => 'artikler',
        'paged'             => $paged
    );

    $wp_query = new WP_Query( $query_args);

    if (!isset( $wp_query ))
    {
        debug_to_console("Query is NULL!");

        return;
    }

    wp_register_script( 'my_loadmore', plugins_url( 'myloadmore.js', __FILE__ ), array('jquery') );

    $postArray = array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
        'posts' => json_encode( $wp_query->query_vars ), 
        'max_page' => $wp_query->max_num_pages,
        'results' => $wp_query->found_posts
    );

    wp_localize_script( 'my_loadmore', 'wordpress_load_more_params', $postArray);

    wp_enqueue_script( 'my_loadmore' );
}

The jQuery script containing the custom action is this:

jQuery(document).ready(function($)
{
    $(".wordpress_load_more").click(function(){

        var button = $(this), data = {
            action      :   'load_more',
            query       :   wordpress_load_more_params.posts,
            max         :   wordpress_load_more_params.max_page,
            page        :   wordpress_load_more_params.current_page,
            results     :   wordpress_load_more_params.results

        };

        console.log(data);

        $.ajax(
        {
            url     :   wordpress_load_more_params.ajaxurl, 
            type    :   'POST',
            data    :   data,
            beforeSend : function ( xhr ) 
            {
                console.log("Loading");

                button.text('Indlæser...');
            },
            success : function( data )
            {
                console.log("Success");

                if(data) 
                { 
                    console.log("We got data!");
                    console.log(wordpress_load_more_params.current_page);
                    console.log(wordpress_load_more_params.max_page);

                    button.text( 'Flere indlæg' ).prev().before(data); 
                    wordpress_load_more_params.current_page++;

                    if ( wordpress_load_more_params.current_page == wordpress_load_more_params.max_page ) 
                    {
                        console.log("Last page! Remove button");

                        button.remove(); 
                    }

                } else {

                    console.log("No data! Remove button");

                    button.remove();
                }
            },
            error: function() 
            {
                console.log("jQuery error");            
            }
        });
    });
});

The PHP function I can't call using the custom jQuery action is this:

add_action( 'wp_ajax_load_more', 'load_more_ajax_handler' ); 
add_action( 'wp_ajax_nopriv_load_more', 'load_more_ajax_handler' );

function load_more_ajax_handler()
{
    global $wp_query;

    debug_to_console("Finaly, load_more_ajax_handler() function is succesfully called!!!");

    $args = json_decode( stripslashes( $_POST['query'] ), true );

    debug_to_console($args);

    $args['paged'] = $_POST['page'] + 1; // we need next page to be loaded
    $args['post_status'] = 'publish';

    query_posts( $args );

    if( have_posts() ) :

        echo "We have post(s)!";

        while( have_posts() ): the_post();

            the_title();

        endwhile;

    endif;

    debug_to_console("Die!");

    wp_die(); 
} 

According to whatever documentation I read and similar examples I find, I am not able to trigger this PHP function is wp_ajax. How come?

Please find example page where i apply this plugin, right here - https://www.uvjagtpro.dk/arkiv/

  • I try on the page and I see a response. do you solve the problem ? – mmm May 21 '18 at 19:57
  • Not sure I understand you comment. The problem is not solved. Let me know, if I need to elaborate on anything above. – Dougless May 21 '18 at 20:01
  • when I click on "Flere indlæg" I see the AJAX result then for me there is no more problem. – mmm May 21 '18 at 20:30
  • I'm wondering why you're sending that huge object in query parameter? Where only few items could do the work. Can you try with only posts_per_page and post_type? – Sohan Zaman May 21 '18 at 20:32
  • I am also seeing the console data when I click "Flere indlæg". I will note that you do not need to json_decode the query args. The ajax is firing just fine. – Nathan Powell May 21 '18 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.