php - 如何在 "No products were found matching your selection"WooCommerce 消息中添加 HTML

标签 php wordpress woocommerce product

在 WooCommerce 中,“未找到与您的选择匹配的产品”。当循环中没有找到产品时,会出现文本。

但是,我想在文本中添加 HTML,所以我使用 gettext过滤钩。通过 str_ireplace 我可以轻松覆盖文本:

function change_empty_category_text($translated) {
   $translated = str_ireplace ('No products were found matching your selection.', 'sorry! we are not delivering products from this category to you pin code at the moment.', $translated);
   return $translated;
 }
add_filter( 'gettext', 'change_empty_category_text' );

但是,当我想在此文本中添加 HTML 时:

function change_empty_category_text($translated) {
   $translated = str_ireplace ('No products were found matching your selection.', 'sorry! we are not delivering products from this category to you pin code at the moment.\r\nplease visit the following categories instead\r\n<a href = 'www.example.com/category1'>category 1</a>\r\n<a href = 'www.example.com/category2'>category 2</a>\r\n<a href = 'www.example.com/category3'>category 3</a>', $translated);
   return $translated;
 }
add_filter( 'gettext', 'change_empty_category_text' );

没有结果。相反,我得到的文本与替换中写入的文本完全相同。

有什么建议吗?

最佳答案

您要调整的文字可以在 templates/loop/no-products-found.php 中找到,这样你就可以覆盖模板文件 与使用 gettext 过滤器 Hook 不同,因为该 Hook 在每次页面加载时都会执行多次。

但是,还有另一种选择。由于 wc_no_products_found 使用 function_exits,请参阅:/includes/wc-template-functions.php在线 3254-3262 @版本 2.5.0

if ( ! function_exists( 'wc_no_products_found' ) ) {

    /**
     * Handles the loop when no products were found/no product exist.
     */
    function wc_no_products_found() {
        wc_get_template( 'loop/no-products-found.php' );
    }
}

更多信息:What's "function_exists" in Wordpress


因此,我们将使用自己的函数重写该函数,而不是使用函数中通过 wc_get_template() 调用的现有模板文件。

所以你得到:

function wc_no_products_found() {
    echo '<p class="woocommerce-info" style="display:block;">' . 
        __( 'Sorry! we are not delivering products from this category to you pin code at the moment.<br>Please visit the following categories instead', 'woocommerce' ) 
        . '<br><a href ="www.example.com/category2">category 2</a><br><a href="www.example.com/category3">category 3</a></p>';
}

正如您所看到的,输出完全可以根据您的需求进行定制。可能需要 CSS 调整,因为这取决于主题。

代码位于事件子主题(或事件主题)的 functions.php 文件中。

关于php - 如何在 "No products were found matching your selection"WooCommerce 消息中添加 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69551824/

相关文章:

php - 如何判断一个时间范围是否在一个时间范围内? PHP

javascript - 错误: Object #<Object> has no method 'easeInOutCubic' - jquery-ui

javascript - 使用 AngularJS 从 JSON 对象中过滤 HTML

PHP 仅显示与用户 ID 关联的 mysql 表中的行

wordpress - 我希望 WooCommerce 立即将现有的自定义帖子类型视为产品,而无需重新保存每个帖子

php - Woocommerce:数据库恢复后可下载文件消失

php - preg_replace : how to?

php - 如何使用带有 UTF-8 的 Codeigniter 路由(如阿拉伯字符 404)

php - 从查询中增长链接列表

css - Woocommerce Checkout 文本未显示在页面中