Skip to content

Instantly share code, notes, and snippets.

@huanyichuang
Last active March 17, 2019 03:51
Show Gist options
  • Save huanyichuang/714599c4c0bb6bd4a779ce6618bc5729 to your computer and use it in GitHub Desktop.
Save huanyichuang/714599c4c0bb6bd4a779ce6618bc5729 to your computer and use it in GitHub Desktop.
Infinite Scroll 筆記
<?php
<?php
function mxp_ajax_get_next_page_data() {
$max_num_pages = $_POST['max_num_pages'];
$current_page = $_POST['current_page'];
$found_posts = $_POST['found_posts'];
$post_type = $_POST['post_type'];
$taxonomy = $_POST['taxonomy'];
$term = $_POST['term'];
$nonce = $_POST['nonce'];
$not_in = $_POST['not_in'];
$not_in_list = explode(",", $not_in);
if (!wp_verify_nonce($nonce, 'mxp-ajax-nonce')) {
wp_send_json_error(array('code' => 500, 'data' => '', 'msg' => '錯誤的請求'));
}
if (!isset($max_num_pages) || $max_num_pages == "" ||
!isset($current_page) || $current_page == "" ||
!isset($found_posts) || $found_posts == "" ||
$not_in == "") {
wp_send_json_error(array('code' => 500, 'data' => '', 'msg' => '錯誤的請求'));
}
if ( !empty( $term ) && !empty( $taxonomy ) ) {
$tax_query = array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $term,
);
} else {
$tax_query = null;
}
$ids = get_posts(array(
'fields' => 'ids', // Only get post IDs
'posts_per_page' => 3,
'post_type' => $post_type,
'tax_query' => array ( $tax_query ),
'post__not_in' => $not_in_list,
));
$str = '';
foreach ($ids as $key => $id) {
$not_in_list[] = $id;
$title = get_the_title( $id );
$content = mb_substr(get_post_meta($id, 'wctp2018-post-content', true), 0, 40) . "...";
$image_large = get_post_meta($id, 'wctp2018-post-image-large', true);
$str .= '<article id="' . $id . '" class="' . join( ' ', get_post_class( array( 'mb-0' ), $id) ) . '">'
. '<div class="flex flex-wrap py-2">'
. '<img src="' . get_field( 'carousel_thumbnail', $id )['url'] . '" alt="' . get_field( 'carousel_thumbnail', $id )['alt'] . '" class="f-w-33">'
. '<div class="f-w-67 px-2"><h3 class="result-loop-title">' . get_field( 'product_info_group', $id )['product_name'] . '</h3>'
. '<p class="result-loop-rank">' . get_field( 'product_info_group', $id )['buying_ranking'] .'</p>'
. '<p class="result-loop-location">' .get_field( 'buying_info_group', $id )['buying_method']['label'] . '</p>'
. '<a class="cta-btn" href="./' . $id . '">' . esc_html__( 'Product detail', 'brandfugetsu') . '</a>'
. '</div><!-- .flex --></article>';
}
wp_send_json_success( array(
'code' => 200,
'data' => $str,
'not_in_list' => implode(", ", $not_in_list),
)
);
}
add_action('wp_ajax_mxp_ajax_get_next_page_data', 'mxp_ajax_get_next_page_data'); //有登入要加這個
add_action('wp_ajax_nopriv_mxp_ajax_get_next_page_data', 'mxp_ajax_get_next_page_data');
function custom_enqueue_styles() {
wp_enqueue_script('infinite-scroll', get_template_directory_uri() . '/js/load-more.js' , array( 'jquery' ));
wp_localize_script('infinite-scroll', 'infScr', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('mxp-ajax-nonce'),
));
}
add_action('wp_enqueue_scripts', 'custom_enqueue_styles');
<script>
(function($){
$(document).ready(function () {
$('.more_posts').click(function (e) {
e.preventDefault();
$(this).attr('disabled', true);
var that = $(this);
var current_posts = $("#not-in").attr("data-pid").split(",").length;
if (current_posts == infScr.posts.found_posts) {
$(this).text('查詢完畢');
$(this).unbind('click');
return;
}
$("body").waitMe({
effect: "bounce",
text: "Loading...",
});
var data = {
'action': 'mxp_ajax_get_next_page_data',
'nonce': infScr.nonce,
'max_num_pages': infScr.posts.max_num_pages,
'current_page': infScr.posts.current_page,
'found_posts': infScr.posts.found_posts,
'post_type' : infScr.posts.post_type,
'taxonomy' : infScr.posts.tax,
'term' : infScr.posts.term,
'not_in' : $("#not-in").attr("data-pid"),
};
// if (md.is('iOS') && parseInt(md.version('iOS')) == 12) {
// if (md.userAgent() == 'Chrome') {
// location.href = '/page/' + (infScr.posts.current_page + 1) + '/';
// return;
// }
// }
$.post( infScr.ajaxurl, data, function (res) {
if ( res.success ) {
if ( infScr.posts.post_type == 'buying_report') {
$( '.item-result-loop' ).append( res.data.data );
$( '#not-in' ).attr( 'data-pid', res.data.not_in_list );
} else {
$( '#customer-voices' ).append( res.data.data );
}
//history.pushState(null, null, '/page/' + (infScr.posts.current_page + 1) + '/');
infScr.posts.current_page += 1;
that.attr('disabled', false);
} else {
alert('Oops! Sorry error occurred!');
//location.reload();
}
$("body").waitMe('hide');
}).fail(function () {
console.log (data);
alert('Oops! Sorry error occurred! Internet issue.');
});
});
$('.new_posts').click(function () {
location.href = '/';
});
});
}(jQuery));
/*
waitMe - 1.19 [31.10.17]
Author: vadimsva
Github: https://github.com/vadimsva/waitMe
*/
(function (b) {
b.fn.waitMe = function (p) {
return this.each(function () {
function y() { var a = f.attr("data-waitme_id"); f.removeClass("waitMe_container").removeAttr("data-waitme_id"); f.find('.waitMe[data-waitme_id="' + a + '"]').remove() } var f = b(this), z, g, e, r = !1, t = "background-color", u = "", q = "", v, a, w, n = {
init: function () {
function n(a) { l.css({ top: "auto", transform: "translateY(" + a + "px) translateZ(0)" }) } a = b.extend({
effect: "bounce", text: "", bg: "rgba(255,255,255,0.7)", color: "#000", maxSize: "", waitTime: -1, textPos: "vertical",
fontSize: "", source: "", onClose: function () { }
}, p); w = (new Date).getMilliseconds(); v = b('<div class="waitMe" data-waitme_id="' + w + '"></div>'); switch (a.effect) {
case "none": e = 0; break; case "bounce": e = 3; break; case "rotateplane": e = 1; break; case "stretch": e = 5; break; case "orbit": e = 2; r = !0; break; case "roundBounce": e = 12; break; case "win8": e = 5; r = !0; break; case "win8_linear": e = 5; r = !0; break; case "ios": e = 12; break; case "facebook": e = 3; break; case "rotation": e = 1; t = "border-color"; break; case "timer": e = 2; var c = b.isArray(a.color) ?
a.color[0] : a.color; u = "border-color:" + c; break; case "pulse": e = 1; t = "border-color"; break; case "progressBar": e = 1; break; case "bouncePulse": e = 3; break; case "img": e = 1
}"" !== u && (u += ";"); if (0 < e) {
if ("img" === a.effect) q = '<img src="' + a.source + '">'; else for (var d = 1; d <= e; ++d)b.isArray(a.color) ? (c = a.color[d], void 0 == c && (c = "#000")) : c = a.color, q = r ? q + ('<div class="waitMe_progress_elem' + d + '"><div style="' + t + ":" + c + '"></div></div>') : q + ('<div class="waitMe_progress_elem' + d + '" style="' + t + ":" + c + '"></div>'); g = b('<div class="waitMe_progress ' +
a.effect + '" style="' + u + '">' + q + "</div>")
} a.text && (c = b.isArray(a.color) ? a.color[0] : a.color, z = b('<div class="waitMe_text" style="color:' + c + ";" + ("" != a.fontSize ? "font-size:" + a.fontSize : "") + '">' + a.text + "</div>")); var k = f.find("> .waitMe"); k && k.remove(); c = b('<div class="waitMe_content ' + a.textPos + '"></div>'); c.append(g, z); v.append(c); "HTML" == f[0].tagName && (f = b("body")); f.addClass("waitMe_container").attr("data-waitme_id", w).append(v); k = f.find("> .waitMe"); var l = f.find(".waitMe_content"); k.css({ background: a.bg });
"" !== a.maxSize && "none" != a.effect && (c = g.outerHeight(), g.outerWidth(), "img" === a.effect ? (g.css({ height: a.maxSize + "px" }), g.find(">img").css({ maxHeight: "100%" }), l.css({ marginTop: -l.outerHeight() / 2 + "px" })) : a.maxSize < c && ("stretch" == a.effect ? (g.css({ height: a.maxSize + "px", width: a.maxSize + "px" }), g.find("> div").css({ margin: "0 5%" })) : (c = a.maxSize / c - .2, d = "-50%", "roundBounce" == a.effect ? (d = "-75%", a.text && (d = "75%")) : "win8" == a.effect || "timer" == a.effect || "orbit" == a.effect ? (d = "-20%", a.text && (d = "20%")) : "ios" == a.effect &&
(d = "-15%", a.text && (d = "15%")), "rotation" == a.effect && a.text && (d = "75%"), g.css({ transform: "scale(" + c + ") translateX(" + d + ")", whiteSpace: "nowrap" })))); l.css({ marginTop: -l.outerHeight() / 2 + "px" }); if (f.outerHeight() > b(window).height()) {
c = b(window).scrollTop(); var h = l.outerHeight(), m = f.offset().top, x = f.outerHeight(); d = c - m + b(window).height() / 2; 0 > d && (d = Math.abs(d)); 0 <= d - h && d + h <= x ? m - c > b(window).height() / 2 && (d = h) : d = c > m + x - h ? c - m - h : c - m + h; n(d); b(document).scroll(function () {
var a = b(window).scrollTop() - m + b(window).height() /
2; 0 <= a - h && a + h <= x && n(a)
})
} 0 < a.waitTime && setTimeout(function () { y() }, a.waitTime); k.on("destroyed", function () { if (a.onClose && b.isFunction(a.onClose)) a.onClose(f); k.trigger("close", { el: f }) }); b.event.special.destroyed = { remove: function (a) { a.handler && a.handler() } }; return k
}, hide: function () { y() }
}; if (n[p]) return n[p].apply(this, Array.prototype.slice.call(arguments, 1)); if ("object" === typeof p || !p) return n.init.apply(this, arguments)
})
}; b(window).on("load", function () {
b("body.waitMe_body").addClass("hideMe"); setTimeout(function () {
b("body.waitMe_body").find(".waitMe_container:not([data-waitme_id])").remove();
b("body.waitMe_body").removeClass("waitMe_body hideMe")
}, 200)
})
})(jQuery);
</script>
<?php
/*
* 利用 shortcode 的方式輸出具有 infinite scroll 功能的區塊
*/
function results ($atts) {
$a = shortcode_atts(array(
'item' => !empty( get_the_terms( get_the_ID() , 'items' ) )
? get_the_terms( get_the_ID() , 'items' )[0] -> slug : '',
'posts' => 5,
)
, $atts);
$tax_item = get_terms( 'items' );
if ( '' != $a['item'] ) {
$tax_query =
array (
'taxonomy' => 'items',
'field' => 'slug',
'terms' => $a['item'],
);
} else {
$tax_query = null;
}
//上面是因為我有設定自訂 taxonomy 才加的
$args = array(
'post_type' => 'buying_report',
'posts_per_page' => $a['posts'],
// 'paged' => $paged,
'tax_query' => array( $tax_query ),
);
//var_dump( $args );
$output = '';
$the_query = new WP_Query( $args );
$not_in_list = [];
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
/*
* 這裡的資料要轉成 JSON 之後送回前端,之後用來判斷什麼時候載完所有結果
*/
$jsparam = array( //push the data for infinite scroll
'post_type' => $the_query -> query_vars['post_type'],
'tax' => $tax_query['taxonomy'],
'term' => $tax_query['terms'],
'max_num_pages' => $the_query -> max_num_pages,
'found_posts' => $the_query -> found_posts,
'current_page' => $paged
);
$output .= '<script id="queryJson">infScr.posts=' . json_encode( $jsparam ) . ';</script>';
$output .= '<div class="item-result-loop">';
while ( $the_query -> have_posts() ) {
$the_query -> the_post();
$not_in_list[] = get_the_ID();
$term = get_the_terms( get_the_ID() , 'brand_list')[0]->name;
$img = !empty( get_field( 'carousel_thumbnail' ) ) ? '<img src="' . get_field( 'carousel_thumbnail' )['url'] . '" alt="' . get_field( 'carousel_thumbnail' )['alt'] . '" class="f-w-33">'
: get_the_post_thumbnail( get_the_ID(), 'full' ,array( 'class' => 'f-w-33' ));
$output .= '<article id="' . get_the_ID() . '" class="' . join( ' ', get_post_class( array( 'mb-0' ) ) ) . '">'
. '<div class="flex flex-wrap py-2">'
. $img
. '<div class="f-w-67 px-2"><h3 class="result-loop-title">' . get_the_title . '</h3>'
. '<p class="result-loop-content">' . get_the_content() . '</p>'
. '<a class="cta-btn" href="./' . get_the_ID() . '">' . esc_html__( 'Product detail', 'your_text_domain') . '</a>'
. '</div>';
$output .= '</div><!-- .flex --></article>';
}
wp_reset_postdata();
$output .= '</div><!-- .item-result-loop -->';
$output .= '<input id="not-in" data-pid="' . implode( ", ", $not_in_list ) . '" hidden>';
$output .= '<div class="text-center"><a class="cta-btn more_posts">'
. esc_html__( 'More Info' , 'your_text_domain' ) . '</a></div>';
return $output;
}
add_shortcode('result','buying_results');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment