WordPress でオートページャー
○HTML
<p class="more"><a href="javascript:void(0);">more</a></p>
○JS
var now_post_num = 10; var get_post_num = 10; $('.more a').click(function(){ $.ajax({ type: 'post', url: 'https://blog.yuheijotaki.com/wyjp/wp-content/themes/jotaki/more.php', data: { 'now_post_num': now_post_num, 'get_post_num': get_post_num }, success: function(data) { now_post_num = now_post_num + get_post_num; data = JSON.parse(data); $('.postArea').append(data['html']); if (!data['noDataFlg']) { // さらに取得できる場合の処理 } else { // 全件読み込んだ場合の処理 } } }); return false; });
○more.php
<?php require_once("../../../wp-config.php"); $now_post_num = $_POST['now_post_num']; $get_post_num = $_POST['get_post_num']; $next_now_post_num = $now_post_num + $get_post_num; $next_get_post_num = $get_post_num + $get_post_num; $sql = "SELECT $wpdb->posts.ID, $wpdb->posts.post_title, $wpdb->posts.post_content FROM $wpdb->posts WHERE $wpdb->posts.post_type = 'post' AND $wpdb->posts.post_status = 'publish' ORDER BY $wpdb->posts.post_date DESC LIMIT $now_post_num, $get_post_num";$results = $wpdb->get_results($sql); $sql = "SELECT $wpdb->posts.ID, $wpdb->posts.post_title, $wpdb->posts.post_content FROM $wpdb->posts WHERE $wpdb->posts.post_type = 'post' AND $wpdb->posts.post_status = 'publish' ORDER BY $wpdb->posts.post_date DESC LIMIT $next_now_post_num, $next_get_post_num"; $next_results = $wpdb->get_results($sql); $noDataFlg = 0; if ( count($results) < $get_post_num || !count($next_results) ) { $noDataFlg = 1; } $html = ""; foreach ($results as $result) { $html .= get_post_time('Y.m.d','false',$result->ID); // 投稿日時 $html .= get_permalink($result->ID); // リンク $html .= apply_filters('the_title', $result->post_title); //記事タイトル } $returnObj = array(); $returnObj = array( 'noDataFlg' => $noDataFlg, 'html' => $html ); $returnObj = json_encode($returnObj); echo $returnObj;
?>
○参考