2020-08-10
- The Load More button is required in the Dr Reborn project.
- Video source:
- Create the loop in the page template file.
- Google search for ‘wp query loop codex’
- copy the sample code in ‘Standard Loop (Alternate)’ to your template file.
- Create the $args array and pass it to WP_Query($args)
$args = array (‘post_type; => ‘treatment’, // here is the name of CPT
‘paged’ => 1 // start from page 1 when first loaded
);
- Go to the Dashboard->Reading Settings page, set ‘Blog pages show at most’ to 2
- the above is a global setting. For customization, the post_per_page can be set in the $args array.
- Create a div with an id=’posts’ to enclose the loop.
- After the above div, create the Load More button with an id=’load_more’.
- Now refresh the page to see the result of the button.
- Add ajax
- go to https://codex.wordpress.org/AJAX_in_Plugins
- Under the section ‘Ajax on the Administration Side’, copy the sample code.
- Paste the code to functions.php. Change the hook from ‘admin_footer’ to ‘wp_footer’
Note: admin_footer is for the backend, whereas wp-footer is for the frontend - Within the above code, write code for the click event.(7:07)
- Cope and paste the code for ‘add_action( ‘wp_ajax_my_action’, ‘my_action’ )’ (8:59)
- Add url for ajaxurl (10:14)
- Modify function my_action() – (10:52)
- Run the WP_Query loop again, which is same as the page template.
- Append the ajax response to the div with id=’posts’. – (13:06)
- Hide the button when no more posts to display -(14:17)
- find the totoal number of post
- total pages = ceiling of (total posts / post_per_page).
- in the div #posts, add attribute data-count=total pages. -(16:46)
- in my_action_javascript(), retrieve the data-count value.
- var post_count = jQuery(‘#posts’).data(‘count’); -(17:45)
- Important notes extracted from Codex:
- Since WordPress 2.8, there is a hook similar to wp_ajax_(action): wp_ajax_nopriv_(action) executes for users that are not logged in.
- So, if you want it to fire on the front-end for both visitors and logged-in users, you can do this:
add_action( ‘wp_ajax_my_action’, ‘my_action’ );
add_action( ‘wp_ajax_nopriv_my_action’, ‘my_action’ );
