feat(shop): multi-tab product widget lazy REST load
First tab SSR via shared payload; other tabs fetch /shop/frontend/widgets/products on switch like zibll tab product.
This commit is contained in:
@@ -8,163 +8,188 @@ namespace AKSRT\Widgets;
|
||||
defined('ABSPATH') || exit;
|
||||
|
||||
/**
|
||||
* Multi-tab product widget — equivalent to zibll `zib_shop_widget_ui_tab_product`.
|
||||
* Each tab has independent category/discount filter.
|
||||
* Multi-tab product widget — zibll `zib_shop_widget_ui_tab_product` lite.
|
||||
* First tab renders immediately via shared payload; other tabs lazy-load via REST.
|
||||
*/
|
||||
class WidgetProductTab extends \WP_Widget {
|
||||
|
||||
public function __construct() {
|
||||
parent::__construct(
|
||||
'aksrt_product_tab',
|
||||
__('多TAB商品', 'aksrt'),
|
||||
['description' => __('AKSRT 多 TAB 商品列表组件(每 tab 独立筛选)。', 'aksrt')]
|
||||
);
|
||||
}
|
||||
public function __construct() {
|
||||
parent::__construct(
|
||||
'aksrt_product_tab',
|
||||
__('多TAB商品', 'aksrt'),
|
||||
['description' => __('AKSRT 多 TAB 商品列表组件(每 tab 独立筛选 + AJAX)。', 'aksrt')]
|
||||
);
|
||||
}
|
||||
|
||||
public function widget($args, $instance): void {
|
||||
$title = apply_filters('widget_title', $instance['title'] ?? '');
|
||||
$tabs_raw = (string) ($instance['tabs'] ?? '');
|
||||
$per_page = max(1, min(20, (int) ($instance['per_page'] ?? 8)));
|
||||
/**
|
||||
* @return list<array{label:string,cat_ids:string,discount_ids:string,tag_ids:string,orderby:string}>
|
||||
*/
|
||||
private static function parse_tabs(string $tabs_raw): array {
|
||||
$tabs = [];
|
||||
foreach (array_filter(explode("\n", $tabs_raw)) as $line) {
|
||||
$parts = explode('|', trim($line));
|
||||
if (count($parts) >= 1 && trim($parts[0]) !== '') {
|
||||
$tabs[] = [
|
||||
'label' => trim($parts[0]),
|
||||
'cat_ids' => trim($parts[1] ?? ''),
|
||||
'discount_ids' => trim($parts[2] ?? ''),
|
||||
'tag_ids' => trim($parts[3] ?? ''),
|
||||
'orderby' => trim($parts[4] ?? 'date'),
|
||||
];
|
||||
}
|
||||
}
|
||||
return $tabs;
|
||||
}
|
||||
|
||||
// Parse tabs: "Tab Name|cat_ids|discount_ids\n..."
|
||||
$tabs = [];
|
||||
foreach (array_filter(explode("\n", $tabs_raw)) as $line) {
|
||||
$parts = explode('|', trim($line));
|
||||
if (count($parts) >= 1 && trim($parts[0]) !== '') {
|
||||
$tabs[] = [
|
||||
'label' => trim($parts[0]),
|
||||
'cat_ids' => trim($parts[1] ?? ''),
|
||||
'discount_ids' => trim($parts[2] ?? ''),
|
||||
];
|
||||
}
|
||||
}
|
||||
if (empty($tabs)) {
|
||||
return;
|
||||
}
|
||||
public function widget($args, $instance): void {
|
||||
$title = apply_filters('widget_title', (string) ($instance['title'] ?? ''), $instance, $this->id_base);
|
||||
$tabs_raw = (string) ($instance['tabs'] ?? '');
|
||||
$per_page = max(1, min(20, (int) ($instance['per_page'] ?? 8)));
|
||||
$style = sanitize_key((string) ($instance['style'] ?? 'default'));
|
||||
$paginate = sanitize_key((string) ($instance['paginate'] ?? 'ajax'));
|
||||
$tabs = self::parse_tabs($tabs_raw);
|
||||
if (!$tabs) {
|
||||
return;
|
||||
}
|
||||
|
||||
echo $args['before_widget'];
|
||||
if ($title) {
|
||||
echo $args['before_title'] . esc_html($title) . $args['after_title'];
|
||||
}
|
||||
echo $args['before_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|
||||
if ($title !== '') {
|
||||
echo $args['before_title'] . esc_html($title) . $args['after_title']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|
||||
}
|
||||
|
||||
echo '<div class="aksrt-product-tab-widget" data-aksrt-product-tab>';
|
||||
$rest = rest_url('aksrt/v1/shop/frontend/widgets/products');
|
||||
echo '<div class="aksrt-product-tab-widget" data-aksrt-product-tab data-per-page="' . esc_attr((string) $per_page) . '" data-style="' . esc_attr($style) . '" data-paginate="' . esc_attr($paginate) . '" data-rest="' . esc_url($rest) . '">';
|
||||
|
||||
// Tab headers
|
||||
echo '<div class="aksrt-product-tab__headers">';
|
||||
foreach ($tabs as $i => $tab) {
|
||||
$active = $i === 0 ? ' is-active' : '';
|
||||
echo '<button type="button" class="aksrt-product-tab__header' . esc_attr($active) . '" data-tab-index="' . esc_attr((string) $i) . '">';
|
||||
echo esc_html($tab['label']);
|
||||
echo '</button>';
|
||||
}
|
||||
echo '</div>';
|
||||
echo '<div class="aksrt-product-tab__headers index-tab">';
|
||||
foreach ($tabs as $i => $tab) {
|
||||
$active = $i === 0 ? ' is-active' : '';
|
||||
echo '<button type="button" class="aksrt-product-tab__header' . esc_attr($active) . '" data-tab-index="' . esc_attr((string) $i) . '"';
|
||||
echo ' data-cat-ids="' . esc_attr($tab['cat_ids']) . '"';
|
||||
echo ' data-discount-ids="' . esc_attr($tab['discount_ids']) . '"';
|
||||
echo ' data-tag-ids="' . esc_attr($tab['tag_ids']) . '"';
|
||||
echo ' data-orderby="' . esc_attr(sanitize_key($tab['orderby'] ?: 'date')) . '"';
|
||||
echo '>' . esc_html($tab['label']) . '</button>';
|
||||
}
|
||||
echo '</div>';
|
||||
|
||||
// Tab panels
|
||||
foreach ($tabs as $i => $tab) {
|
||||
$hidden = $i > 0 ? ' style="display:none"' : '';
|
||||
echo '<div class="aksrt-product-tab__panel" data-tab-index="' . esc_attr((string) $i) . '"' . $hidden . '>';
|
||||
foreach ($tabs as $i => $tab) {
|
||||
$hidden = $i > 0 ? ' style="display:none"' : '';
|
||||
$loaded = $i === 0 ? '1' : '0';
|
||||
echo '<div class="aksrt-product-tab__panel" data-tab-index="' . esc_attr((string) $i) . '" data-loaded="' . esc_attr($loaded) . '"' . $hidden . '>';
|
||||
|
||||
$query_args = [
|
||||
'post_type' => 'aksrt_product',
|
||||
'post_status' => 'publish',
|
||||
'posts_per_page' => $per_page,
|
||||
'orderby' => 'date',
|
||||
'order' => 'DESC',
|
||||
];
|
||||
if ($i === 0) {
|
||||
$inst = [
|
||||
'per_page' => $per_page,
|
||||
'orderby' => sanitize_key($tab['orderby'] ?: 'date'),
|
||||
'order' => 'DESC',
|
||||
'cat_ids' => $tab['cat_ids'],
|
||||
'tag_ids' => $tab['tag_ids'],
|
||||
'discount_ids' => $tab['discount_ids'],
|
||||
'style' => $style,
|
||||
'paginate' => $paginate,
|
||||
];
|
||||
$payload = class_exists('\AKSRT\Widgets\WidgetProductList')
|
||||
? WidgetProductList::query_payload($inst, 1)
|
||||
: ['html' => '', 'paginate_html' => ''];
|
||||
echo '<div class="ajaxpager aksrt-product-widget__grid product-lists-row aksrt-product-widget--' . esc_attr($style) . '" data-aksrt-ajaxpager>';
|
||||
echo $payload['html']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|
||||
echo $payload['paginate_html']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|
||||
echo '<div class="post_ajax_loader" data-aksrt-ajax-loader data-aksrt-ajax-loader-hide hidden></div>';
|
||||
echo '</div>';
|
||||
} else {
|
||||
echo '<div class="ajaxpager aksrt-product-widget__grid product-lists-row aksrt-product-widget--' . esc_attr($style) . ' is-lazy" data-aksrt-ajaxpager>';
|
||||
echo '<div class="post_ajax_loader" data-aksrt-ajax-loader></div>';
|
||||
echo '<div class="ajax-pag hide"><div class="next-page ajax-next"><a href="#"></a></div></div>';
|
||||
echo '</div>';
|
||||
}
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
$tax_query = [];
|
||||
$cat_ids = array_filter(array_map('intval', explode(',', $tab['cat_ids'])));
|
||||
$discount_ids = array_filter(array_map('intval', explode(',', $tab['discount_ids'])));
|
||||
if (!empty($cat_ids)) {
|
||||
$tax_query[] = ['taxonomy' => 'aksrt_product_cat', 'field' => 'term_id', 'terms' => $cat_ids];
|
||||
}
|
||||
if (!empty($discount_ids)) {
|
||||
$tax_query[] = ['taxonomy' => 'shop_discount', 'field' => 'term_id', 'terms' => $discount_ids];
|
||||
}
|
||||
if (!empty($tax_query)) {
|
||||
$query_args['tax_query'] = $tax_query;
|
||||
}
|
||||
// Lightweight tab switch + lazy REST load (no inline product HTML duplication).
|
||||
echo '<script>(function(){';
|
||||
echo 'var root=document.currentScript&&document.currentScript.parentElement;if(!root)return;';
|
||||
echo 'var rest=root.getAttribute("data-rest")||"";';
|
||||
echo 'var per=root.getAttribute("data-per-page")||"8";';
|
||||
echo 'var style=root.getAttribute("data-style")||"default";';
|
||||
echo 'var paginate=root.getAttribute("data-paginate")||"ajax";';
|
||||
echo 'function loadPanel(panel,btn){if(!panel||panel.getAttribute("data-loaded")==="1")return;';
|
||||
echo 'var grid=panel.querySelector("[data-aksrt-ajaxpager]");if(!grid||!rest)return;';
|
||||
echo 'var qs=new URLSearchParams({page:"1",per_page:per,style:style,paginate:paginate,';
|
||||
echo 'orderby:btn.getAttribute("data-orderby")||"date",order:"DESC",';
|
||||
echo 'cat_ids:btn.getAttribute("data-cat-ids")||"",tag_ids:btn.getAttribute("data-tag-ids")||"",';
|
||||
echo 'discount_ids:btn.getAttribute("data-discount-ids")||""});';
|
||||
echo 'var url=rest+(rest.indexOf("?")>-1?"&":"?")+qs.toString();';
|
||||
echo 'grid.classList.add("is-ajax-loading");';
|
||||
echo 'fetch(url,{credentials:"same-origin",headers:{Accept:"application/json","X-WP-Nonce":(window.aksrtData&&aksrtData.restNonce)||""}})';
|
||||
echo '.then(function(r){return r.json()}).then(function(j){';
|
||||
echo 'var d=(j&&j.data&&(j.data.data||j.data))||j||{};';
|
||||
echo 'var html=d.html||""; var pag=d.paginate_html||d.paginateHtml||"";';
|
||||
echo 'var loader=grid.querySelector("[data-aksrt-ajax-loader]");';
|
||||
echo 'grid.innerHTML=""; if(html)grid.insertAdjacentHTML("beforeend",html); if(pag)grid.insertAdjacentHTML("beforeend",pag);';
|
||||
echo 'if(loader)grid.appendChild(loader); panel.setAttribute("data-loaded","1"); grid.classList.remove("is-ajax-loading");';
|
||||
echo '}).catch(function(){grid.classList.remove("is-ajax-loading");});}';
|
||||
echo 'root.querySelectorAll(".aksrt-product-tab__header").forEach(function(btn){';
|
||||
echo 'btn.addEventListener("click",function(){';
|
||||
echo 'root.querySelectorAll(".aksrt-product-tab__header").forEach(function(b){b.classList.remove("is-active")});';
|
||||
echo 'root.querySelectorAll(".aksrt-product-tab__panel").forEach(function(p){p.style.display="none"});';
|
||||
echo 'btn.classList.add("is-active");';
|
||||
echo 'var idx=btn.getAttribute("data-tab-index");';
|
||||
echo 'var panel=root.querySelector(\'.aksrt-product-tab__panel[data-tab-index="\'+idx+\'"]\');';
|
||||
echo 'if(panel){panel.style.display="";loadPanel(panel,btn);}';
|
||||
echo '});});';
|
||||
echo '})();</script>';
|
||||
|
||||
$products = new \WP_Query($query_args);
|
||||
if ($products->have_posts()) {
|
||||
echo '<div class="aksrt-product-widget__grid">';
|
||||
while ($products->have_posts()) {
|
||||
$products->the_post();
|
||||
$pid = get_the_ID();
|
||||
$card = class_exists('\AKSRT\Shop\Shop')
|
||||
? \AKSRT\Shop\Shop::get_instance()->build_product_card_view($pid)
|
||||
: [];
|
||||
$price = (float) ($card['price'] ?? 0);
|
||||
$image = $card['image'] ?? '';
|
||||
echo '<div class="aksrt-product-widget__item">';
|
||||
if ($image) {
|
||||
echo '<a href="' . esc_url(get_permalink($pid)) . '" class="aksrt-product-widget__thumb">';
|
||||
echo '<img src="' . esc_url($image) . '" alt="' . esc_attr(get_the_title($pid)) . '" loading="lazy">';
|
||||
echo '</a>';
|
||||
}
|
||||
echo '<div class="aksrt-product-widget__info">';
|
||||
echo '<a href="' . esc_url(get_permalink($pid)) . '" class="aksrt-product-widget__title">' . esc_html(get_the_title($pid)) . '</a>';
|
||||
echo '<span class="aksrt-product-widget__price">¥' . esc_html(number_format_i18n($price, 2)) . '</span>';
|
||||
echo '</div></div>';
|
||||
}
|
||||
echo '</div>';
|
||||
} else {
|
||||
echo '<p class="aksrt-product-widget__empty">' . esc_html__('暂无商品', 'aksrt') . '</p>';
|
||||
}
|
||||
echo '</div>';
|
||||
echo $args['after_widget']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
|
||||
}
|
||||
|
||||
echo '</div>';
|
||||
wp_reset_postdata();
|
||||
}
|
||||
public function form($instance): void {
|
||||
$defaults = [
|
||||
'title' => __('商品精选', 'aksrt'),
|
||||
'tabs' => "热门推荐|\n最新上架|",
|
||||
'per_page' => 8,
|
||||
'style' => 'default',
|
||||
'paginate' => 'ajax',
|
||||
];
|
||||
$instance = wp_parse_args($instance, $defaults);
|
||||
?>
|
||||
<p>
|
||||
<label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_html_e('标题:', 'aksrt'); ?></label>
|
||||
<input class="widefat" type="text" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" value="<?php echo esc_attr((string) $instance['title']); ?>">
|
||||
</p>
|
||||
<p>
|
||||
<label for="<?php echo esc_attr($this->get_field_id('tabs')); ?>"><?php esc_html_e('TAB配置(每行: 名称|分类ID|优惠ID|标签ID|排序):', 'aksrt'); ?></label>
|
||||
<textarea class="widefat" rows="5" id="<?php echo esc_attr($this->get_field_id('tabs')); ?>" name="<?php echo esc_attr($this->get_field_name('tabs')); ?>"><?php echo esc_textarea((string) $instance['tabs']); ?></textarea>
|
||||
</p>
|
||||
<p>
|
||||
<label for="<?php echo esc_attr($this->get_field_id('per_page')); ?>"><?php esc_html_e('每页数量:', 'aksrt'); ?></label>
|
||||
<input class="tiny-text" type="number" min="1" max="20" id="<?php echo esc_attr($this->get_field_id('per_page')); ?>" name="<?php echo esc_attr($this->get_field_name('per_page')); ?>" value="<?php echo esc_attr((string) $instance['per_page']); ?>">
|
||||
</p>
|
||||
<p>
|
||||
<label for="<?php echo esc_attr($this->get_field_id('style')); ?>"><?php esc_html_e('样式:', 'aksrt'); ?></label>
|
||||
<select class="widefat" id="<?php echo esc_attr($this->get_field_id('style')); ?>" name="<?php echo esc_attr($this->get_field_name('style')); ?>">
|
||||
<option value="default" <?php selected($instance['style'], 'default'); ?>><?php esc_html_e('默认', 'aksrt'); ?></option>
|
||||
<option value="card" <?php selected($instance['style'], 'card'); ?>><?php esc_html_e('卡片', 'aksrt'); ?></option>
|
||||
<option value="mini" <?php selected($instance['style'], 'mini'); ?>><?php esc_html_e('迷你', 'aksrt'); ?></option>
|
||||
</select>
|
||||
</p>
|
||||
<p>
|
||||
<label for="<?php echo esc_attr($this->get_field_id('paginate')); ?>"><?php esc_html_e('分页:', 'aksrt'); ?></label>
|
||||
<select class="widefat" id="<?php echo esc_attr($this->get_field_id('paginate')); ?>" name="<?php echo esc_attr($this->get_field_name('paginate')); ?>">
|
||||
<option value="ajax" <?php selected($instance['paginate'], 'ajax'); ?>><?php esc_html_e('AJAX', 'aksrt'); ?></option>
|
||||
<option value="none" <?php selected($instance['paginate'], 'none'); ?>><?php esc_html_e('无', 'aksrt'); ?></option>
|
||||
</select>
|
||||
</p>
|
||||
<?php
|
||||
}
|
||||
|
||||
// Tab switching JS
|
||||
echo '<script>';
|
||||
echo '(function(){';
|
||||
echo 'var w=document.currentScript.parentElement;';
|
||||
echo 'w.querySelectorAll(".aksrt-product-tab__header").forEach(function(btn){';
|
||||
echo 'btn.addEventListener("click",function(){';
|
||||
echo 'w.querySelectorAll(".aksrt-product-tab__header").forEach(function(b){b.classList.remove("is-active")});';
|
||||
echo 'w.querySelectorAll(".aksrt-product-tab__panel").forEach(function(p){p.style.display="none"});';
|
||||
echo 'btn.classList.add("is-active");';
|
||||
echo 'var idx=btn.getAttribute("data-tab-index");';
|
||||
echo 'var panel=w.querySelector(".aksrt-product-tab__panel[data-tab-index=\'\"+idx+\"\']");';
|
||||
echo 'if(panel)panel.style.display="";';
|
||||
echo '});';
|
||||
echo '});';
|
||||
echo '})();';
|
||||
echo '</script>';
|
||||
|
||||
echo '</div>';
|
||||
echo $args['after_widget'];
|
||||
}
|
||||
|
||||
public function form($instance): void {
|
||||
$defaults = [
|
||||
'title' => __('商品精选', 'aksrt'),
|
||||
'tabs' => "热门推荐|\n最新上架|",
|
||||
'per_page' => 8,
|
||||
];
|
||||
$instance = wp_parse_args($instance, $defaults);
|
||||
?>
|
||||
<p>
|
||||
<label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php esc_html_e('标题:', 'aksrt'); ?></label>
|
||||
<input class="widefat" type="text" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" value="<?php echo esc_attr($instance['title']); ?>">
|
||||
</p>
|
||||
<p>
|
||||
<label for="<?php echo esc_attr($this->get_field_id('tabs')); ?>"><?php esc_html_e('TAB配置(每行: 名称|分类ID|优惠ID):', 'aksrt'); ?></label>
|
||||
<textarea class="widefat" rows="5" id="<?php echo esc_attr($this->get_field_id('tabs')); ?>" name="<?php echo esc_attr($this->get_field_name('tabs')); ?>"><?php echo esc_textarea($instance['tabs']); ?></textarea>
|
||||
</p>
|
||||
<p>
|
||||
<label for="<?php echo esc_attr($this->get_field_id('per_page')); ?>"><?php esc_html_e('每页数量:', 'aksrt'); ?></label>
|
||||
<input class="tiny-text" type="number" min="1" max="20" id="<?php echo esc_attr($this->get_field_id('per_page')); ?>" name="<?php echo esc_attr($this->get_field_name('per_page')); ?>" value="<?php echo esc_attr((string) $instance['per_page']); ?>">
|
||||
</p>
|
||||
<?php
|
||||
}
|
||||
|
||||
public function update($new_instance, $old_instance): array {
|
||||
return [
|
||||
'title' => sanitize_text_field($new_instance['title'] ?? ''),
|
||||
'tabs' => sanitize_textarea_field($new_instance['tabs'] ?? ''),
|
||||
'per_page' => max(1, min(20, (int) ($new_instance['per_page'] ?? 8))),
|
||||
];
|
||||
}
|
||||
public function update($new_instance, $old_instance): array {
|
||||
return [
|
||||
'title' => sanitize_text_field((string) ($new_instance['title'] ?? '')),
|
||||
'tabs' => sanitize_textarea_field((string) ($new_instance['tabs'] ?? '')),
|
||||
'per_page' => max(1, min(20, (int) ($new_instance['per_page'] ?? 8))),
|
||||
'style' => sanitize_key((string) ($new_instance['style'] ?? 'default')),
|
||||
'paginate' => sanitize_key((string) ($new_instance['paginate'] ?? 'ajax')),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user