Templates 你能用模板零件制作短代码吗?

Templates 你能用模板零件制作短代码吗?,templates,woocommerce,shortcode,Templates,Woocommerce,Shortcode,我对创建短代码感兴趣,它基本上填充了WooCommerce签出的模板部分。例如,在my child主题的functions.php中: function shortcode_review_order() { //get the template part from woocommerce/templates/checkout/review-order.php wc_get_template_part('checkout/review-order'); } add_shortcod

我对创建短代码感兴趣,它基本上填充了WooCommerce签出的模板部分。例如,在my child主题的functions.php中:

function shortcode_review_order() {
    //get the template part from woocommerce/templates/checkout/review-order.php
    wc_get_template_part('checkout/review-order');
}
add_shortcode( 'custom_review_order', 'shortcode_review_order' );
…然后在我的页面中

<div>[custom_review_order]</div>
[自定义审查订单]
当我试着这样做时,我的结账页面上什么也没有出现


这可能吗?

您的代码中几乎没有错误

首先,应该使用
init
hook添加一个短代码

add_action( 'init', 'add_shortcodes' );
function add_shortcodes(){
    add_shortcode( 'custom_review_order', 'shortcode_review_order' );
}
然后您缺少模板的
.php
部分。它还需要如下所示的数组参数。使用
wc\u get\u模板
可能会得到更准确的结果

function shortcode_review_order(){
    wc_get_template( 'checkout/review-order.php', array( 'checkout' => WC()->checkout() ) );
}

要了解有关如何正确使用其模板的更多信息,请在插件上搜索每个模板。你会看到它是如何被使用的。你可以得到一个关于如何自己使用它的提示。

我发现wc_get_模板会回显模板,相反,对于返回模板的短代码更好。您可以使用:

$string=wc\u get\u template\u html($template\u name、$args、$template\u path、$default\u path)

它“类似于wc_get_模板,但返回HTML而不是输出。”


谢谢。这起作用了。事实上,我花了3个小时的大部分时间阅读和试验这个方法和其他方法,但我发现的示例中没有一个包括
add_操作('init','add_shortcode')和您添加的其他内容。或者我只是运气不好,无法找到代码示例:普威尔。我在插件中搜索了
add\u短代码
。。。看到它在
init
;上)我想那是幸运的。哈哈,你来得太早了。在签出页面上,但仅在编辑模式下,当我在文本编辑器中包含此短代码并保存时,我得到
致命错误:未捕获错误:在/wp content/plugins/woocommerce/templates/Checkout/review order.php中调用null上的成员函数get_cart(),然后是堆栈跟踪。我肯定遗漏了一些其他的“成分”,但我似乎无法通过这个模糊的错误信息找到原因(你所说的编辑模式是什么意思?你使用的是某种前端编辑器吗?只是WordPress中的编辑器。我正在使用WoodPress编辑器以文本(而不是视觉)模式编辑WooCommerce签出页面。我添加了
[自定义审查顺序]
shortcode对其进行编码并保存,这就是错误发生的时间。但当我在浏览器中加载签出页面时,该快捷码会呈现。