wc_get_template返回空值

3

我似乎无法让wc_get_template()返回我的页面模板。我确定路径在我的子主题文件夹中存储的位置是正确的,但运行时我得到了NULL。你能看出这里有什么问题吗?

public function endpoint_content() { 

    // The template name. 
    $template_name = 'Students Details'; 

    // (default: array()) 
    $args = array(); 

    // The template path. 
    $template_path =  get_stylesheet_directory().'/woocommerce/myaccount/add_students.php';

    // NOTICE! Understand what this does before running. 
    $res = wc_get_template($template_name, $args, $template_path, $template_path);

    var_dump($res); 
}

查看 wc_get_template() 函数的代码,它不会返回任何东西。在其他文档中,它指定了“返回:void”。 - Henders
1
也许可以看一下wc_get_template_html(),它是“...类似于wc_get_template,但返回HTML而不是输出它”。 - Henders
@Henders,谢谢您的回复。我已经尝试了wc_get_template_html(),但它返回了string(0) "",所以我想知道这可能是因为它是一个子主题。如果我使用include语句,它可以正常工作。但我不知道这是否是良好的实践。 - Alex Kirwan
说实话我也不确定。很可能是你传递的参数有些无效。我只是快速浏览了一下代码,看看它应该返回什么。 - Henders
1个回答

7
您正在向wc_get_template()传递错误的参数。

  1. $template_name 是完整名称,如 myaccount/student-details.php
  2. $template_path 为空字符串。通常,WC会在主题的woocommerce文件夹中查找
  3. $default_path 这是您插件模板的路径。在这种情况下,请在我为您创建的插件的根文件夹中添加一个templates文件夹,详见您在原问题中的描述。

更新后的函数如下:

/**
 * Endpoint HTML content.
 */
public function endpoint_content() {    

    // The template name. 
    $template_name = 'myaccount/student-details.php'; 

    // default args
    $args = array(); 

    // default template
    $template_path = ''; // use default which is usually "woocommerce"

    // default path (look in plugin file!)
    $default_path = untrailingslashit( plugin_dir_path(__FILE__) ) . '/templates/';

    // call the template
    wc_get_template($template_name, $args, $template_path, $default_path);

}

这里有一个示例模板 wc-your-custom-endpoint-plugin/templates/student-details.php:

<?php
/**
 * Template
 * 
 * @author      Kathy Darling
 * @package     WC_Custom_Endpoint/Templates
 * @version     0.1.0
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
?>

<?php do_action( 'wc_custom_endpoint_before_student_details' ); ?>

<p><?php _e( 'Hello World!', 'wc-custom-endpoint' ); ?><p>

<?php do_action( 'wc_custom_endpoint_after_student_details' ); ?>

再次感谢helgatheviking,你又救了我。 :D - Alex Kirwan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接