Wordpress category post AJAX Pagination

后端 未结 2 1150
梦毁少年i
梦毁少年i 2021-01-21 21:55

I\'m really struggling to find a way to create pagination with ajax for my Wordpress posts. The solutions that I have found do not work.

To be more informative about th

2条回答
  •  遇见更好的自我
    2021-01-21 22:44

    What you need to do is to prevent default on the pagination links, and send an AJAX request to get the posts. Wordpress works in this way for AJAX: you send all your requests to wp-admin/admin-ajax.php with an action parameter that will identify the request in order to catch it in functions.php using wp_ajax_nopriv_my_action and wp_ajax_my_action hooks.

    So basically you will do this in your template file:

    
    

    You'll have to change classes names / attributes etc depending of your template.

    And on the functions.php side:

    function my_ajax_navigation() {
        $requested_page = intval($_POST['page']);
        $posts_per_page = intval($_POST['posts_per_page']) - 1;
        $posts = get_posts(array(
            'posts_per_page' => $posts_per_page,
            'offset' => $page * $posts_per_page
        ));
        foreach ($posts as $post) {
            setup_postdata( $post );
            // DISPLAY POST HERE
            // good thing to do would be to include your post template
        }
        exit;
    }
    add_action( 'wp_ajax_ajax_pagination', 'my_ajax_navigation' );
    add_action( 'wp_ajax_nopriv_ajax_paginationr', 'my_ajax_navigation' );
    

    The thing is to query the posts of the page requested (so we calculate the offset from the page number and the posts per page option), and display them with the template you use for single posts.

    You may want to manipulate the browser history too, for that you should check on the History API.

提交回复
热议问题