[英]Array index is printed out when using 'add_args' in WooCommerce/Wordpress paginate_links()
我一直試圖在 inte.net 上搜索答案,但沒有找到。 我為 WooCommerce 存檔頁面創建了一個自定義過濾器,它由 ajax 加載。除分頁外,一切正常。
當刷新頁面並具有多個同名參數(例如 example.com/category/filter_fabric=cotton&filter_fabric=polyester)時,分頁鏈接僅考慮最后一個參數(在本例中為 polyester)。 通過進入 woocommerce 中的 loop/pagination.php 並添加以下內容,我能夠解決這個問題:
`//Get parameters from URL
$url_parameters = $_SERVER['QUERY_STRING'];
$paginate_add_args = proper_parse_str($url_parameters);
//@TODO: the "&" that are supposed to come from array within array/nested array, i.e. filter_fabric are becoming "%5B0%5D" instead of "&"`
然后我在 paginate_links() 的“add_args”中傳遞了該參數(也在 loop/pagination.php 中),如下所示:
`<nav class="woocommerce-pagination">
<?php
echo paginate_links( apply_filters( 'woocommerce_pagination_args', array( // WPCS: XSS ok.
'base' => $base,
'format' => $format,
'add_args' => $paginate_add_args,
'current' => max( 1, $current ),
'total' => $total,
'prev_text' => '<i class="fa fa-angle-left"></i>',
'next_text' => '<i class="fa fa-angle-right"></i>',
'type' => 'list',
'end_size' => 2,
'mid_size' => 1,
) ) );
?>
</nav>
`
這解決了我的參數的所有實例都被加載到鏈接中的問題,但問題是由於我的 filter_fabric 參數變成了一個數組,它打印出 URL 中的數組索引,如下所示:
example.com/category/page/2/filter_fabric%5B0%5D=cotton&filter_fabric%5B1%5D=滌綸
有誰知道如何解決這個問題? 任何事情都會有很大幫助!
我試過使用上面提到的方法。
更新/編輯#1所以我想我通過這種方法設法修復了分頁鏈接:
//Get parameters from URL
$url_parameters = $_SERVER['QUERY_STRING'];
$paginate_add_args = proper_parse_str($url_parameters);
# Function that turns the array items into string, like this
# e.g. array(filter_fabric => array(cotton, polyester, linen))
# into:
# array(filter_fabric => 'cotton&filter_fabric=polyester&filter_fabric=linen')
$walk = function(&$item, $key) {
if (is_array($item)) {
$item = implode('&' . $key . '=', $item);
}
};
array_walk($paginate_add_args, $walk);
//var_dump($array); //Outputs: 'cotton&filter_fabric=polyester'
這實際上正確地呈現了分頁鏈接,鏈接是:
'example.com/category/page/2/?filter_fabric=cotton&filter_fabric=polyester'
但...
當我實際單擊該鏈接時,頁面僅加載最后一個參數。 它幾乎看起來好像只用最后一個參數重定向,也就是說,進入這個:
'example.com/category/page/2/?filter_fabric=polyester'
任何人都知道為什么會這樣?
更新/編輯#2我想我設法通過添加remove_action('template_redirect', 'redirect_canonical')
解決了這個問題請查看此鏈接中的答案: Adding multiple values to a query variable in WordPress
您可以修改 output 的 paginate_links() function 以通過在將參數添加到分頁鏈接之前對參數進行編碼來刪除數組索引。 您可以使用 http_build_query() function 執行此操作。方法如下:
<nav class="woocommerce-pagination">
<?php
$paginate_add_args = http_build_query($paginate_add_args);
echo paginate_links( apply_filters( 'woocommerce_pagination_args', array( // WPCS: XSS ok.
'base' => $base,
'format' => $format,
'add_args' => $paginate_add_args,
'current' => max( 1, $current ),
'total' => $total,
'prev_text' => '<i class="fa fa-angle-left"></i>',
'next_text' => '<i class="fa fa-angle-right"></i>',
'type' => 'list',
'end_size' => 2,
'mid_size' => 1,
) ) );
?>
這將以查詢字符串格式對 URL 參數進行編碼,因此它不會顯示 URL 中的數組索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.