首页 > 解决方案 > WordPress 自定义端点模板不加载

问题描述

我正在尝试将自定义模板添加account-details.php到我的帐户区域中的新端点。

我首先添加了新的帐户详细信息端点:

add_action( 'init', 'co_add_my_account_endpoint' );

function co_add_my_account_endpoint() {
    add_rewrite_endpoint( 'account-details', EP_ROOT | EP_PAGES );
}

在这里我添加了自定义模板:

add_filter( 'wc_get_template', 'co_custom_endpoint', 10, 5 );
/**
* Add account details custom template
*
* @param $located
* @param $template_name
* @param $args
* @param $template_path
* @param $default_path
* @since 2.0
* @return string $located
*/
function co_custom_endpoint($located, $template_name, $args, $template_path, $default_path) {
    global $wp;

    if( 'myaccount/my-account.php' == $template_name ) {
        $located = wc_locate_template( 'myaccount/account-details.php', $template_path, JGTB_PATH . 'templates/' );
    }

    return $located;
}

最后我手动刷新重写规则,但我的模板仍然没有加载到前端。任何人都可以看到我做错了什么?我在 stack-overflow 上找到了关于此的其他帖子,但如果我复制完全相同,它也对我不起作用..有什么想法吗?

非常感谢任何帮助!

标签: phpwordpressfrontend

解决方案


将以下代码用于您的活动主题的function.php.

function custom_account_details_page_endpoints() {
    add_rewrite_endpoint( 'account-details', EP_ROOT | EP_PAGES );
}

add_action( 'init', 'custom_account_details_page_endpoints' );

function custom_account_details_query_vars( $vars ) {
    $vars[] = 'account-details';

    return $vars;
}

add_filter( 'query_vars', 'custom_account_details_query_vars', 0 );

function custom_account_details_query_vars_flush_rewrite_rules() {
    flush_rewrite_rules();
}

add_action( 'wp_loaded', 'custom_account_details_query_vars_flush_rewrite_rules' );

请务必将account-details.php文件放在myaccount文件夹中。

function custom_account_details_endpoint_content() {
    include 'woocommerce/myaccount/account-details.php'; 
}

add_action( 'woocommerce_account_account-details_endpoint', 'custom_account_details_endpoint_content' );

通过这样做,请确保通过转到仪表板 -> 设置 -> 永久链接并单击来更新永久链接save settings


推荐阅读