Включить проблему с файлом пользовательского шаблона на странице моей учетной записи Woocommerce

Я пытаюсь добавить файл шаблона, расположенный в моей активной дочерней теме:

childtheme/woocommerce/myaccount/order-a-kit.php

Функция также использует echo "Hello World", который отображается успешно, но не включенный файл шаблона php.

Я пробовал эти:

include($_SERVER['DOCUMENT_ROOT']."twentyseventeen-child/woocommerce/myaccount/order-a-kit.php");

include($get_stylesheet_directory_uri()."twentyseventeen-child/woocommerce/myaccount/order-a-kit.php");

include 'twentyseventeen-child/woocommerce/myaccount/order-a-kit.php';

Содержимое order-a-kit.php очень простое, я просто пытаюсь включить этот файл:

<?php
?>

<div>
    <p>
        Look at me
    </p>
</div>

Это мой раздел function.php, и все работает так, как должно, за исключением функции включения внизу:

add_filter( 'woocommerce_account_menu_items', 'add_my_menu_items', 99, 1 );

function add_my_menu_items( $items ) {
    $my_items = array(
    //  endpoint   => label
        'order-a-kit' => __( 'Order A Kit', 'woocommerce'),
        'orders' => __( 'Order History', 'my_plugin' ),
    );

    $my_items = array_slice( $items, 0, 1, true ) +
        $my_items +
        array_slice( $items, 1, count( $items ), true );

    return $my_items;
}


//adding custom endpoint 

function my_custom_endpoints() {
    add_rewrite_endpoint( 'order-a-kit', EP_ROOT | EP_PAGES );
}

add_action( 'init', 'my_custom_endpoints' );

function my_custom_query_vars( $vars ) {
    $vars[] = 'order-a-kit';

    return $vars;
}

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

function my_custom_flush_rewrite_rules() {
    flush_rewrite_rules();
}

add_action( 'wp_loaded', 'my_custom_flush_rewrite_rules' );

//including custom endpoint

function my_custom_endpoint_content() {
    include 'twentyseventeen-child/woocommerce/myaccount/order-a-kit.php';
    echo '<p>Hello World!</p>';
}

add_action( 'woocommerce_account_order-a-kit_endpoint', 'my_custom_endpoint_content' );


?>

Любая помощь приветствуется.


person Tony Garand    schedule 21.03.2018    source источник


Ответы (3)


Поскольку папка «woocommerce» находится внутри вашей темы в виде файла function.php, вам просто нужно использовать:

include 'woocommerce/myaccount/order-a-kit.php';

См. этот связанный ответ: WooCommerce: добавление пользовательского шаблона клиенту страницы аккаунта

person LoicTheAztec    schedule 21.03.2018
comment
Там я переосмыслил это, я решил, что мне нужно быть более конкретным в пути, так как он был в дочерней теме. Спасибо. - person Tony Garand; 21.03.2018
comment
@TonyGarand вы можете заменить include на include_once, если хотите… Теперь require и require_once более строгие (если путь не совпадает, это выдаст фатальную ошибку, и скрипт остановится)… см. эту тему: stackoverflow.com/questions/2418473/ - person LoicTheAztec; 21.03.2018

Попробуй это

require_once plugin_dir_path( dirname( __FILE__ ) ) . 'woocommerce/myaccount/order-a-kit.php';
person Andrew Schultz    schedule 21.03.2018
comment
Спасибо за ваш комментарий! я прошу ваших рассуждений требовать один раз против включения? - person Tony Garand; 21.03.2018
comment
@TonyGarand вы можете прочитать об этом здесь stackoverflow.com/questions/2418473/. Require_once проверяет, был ли файл уже включен или нет. - person Andrew Schultz; 21.03.2018

Вы можете добавить этот код в файл function.php вашей темы:

class My_Custom_My_Account_Endpoint {
/**
 * Custom endpoint name.
 *
 * @var string
 */
public static $endpoint = 'Your Desired Link';
/**
 * Plugin actions.
 */
public function __construct() {
    // Actions used to insert a new endpoint in the WordPress.
    add_action( 'init', array( $this, 'add_endpoints' ) );
    add_filter( 'query_vars', array( $this, 'add_query_vars' ), 0 );
    // Change the My Accout page title.
    add_filter( 'the_title', array( $this, 'endpoint_title' ) );
    // Insering your new tab/page into the My Account page.
    add_filter( 'woocommerce_account_menu_items', array( $this, 'new_menu_items' ) );
    add_action( 'woocommerce_account_' . self::$endpoint .  '_endpoint', array( $this, 'endpoint_content' ) );
}
/**
 * Register new endpoint to use inside My Account page.
 *
 * @see https://developer.wordpress.org/reference/functions/add_rewrite_endpoint/
 */
public function add_endpoints() {
    add_rewrite_endpoint( self::$endpoint, EP_ROOT | EP_PAGES );
}
/**
 * Add new query var.
 *
 * @param array $vars
 * @return array
 */
public function add_query_vars( $vars ) {
    $vars[] = self::$endpoint;
    return $vars;
}
/**
 * Set endpoint title.
 *
 * @param string $title
 * @return string
 */
public function endpoint_title( $title ) {
    global $wp_query;
    $is_endpoint = isset( $wp_query->query_vars[ self::$endpoint ] );
    if ( $is_endpoint && ! is_admin() && is_main_query() && in_the_loop() && is_account_page() ) {
        // New page title.
        $title = __( 'Your Item Name', 'woocommerce' );
        remove_filter( 'the_title', array( $this, 'endpoint_title' ) );
    }
    return $title;
}
/**
 * Insert the new endpoint into the My Account menu.
 *
 * @param array $items
 * @return array
 */
public function new_menu_items( $items ) {
    // Remove the logout menu item.
    $logout = $items['customer-logout'];
    unset( $items['customer-logout'] );
    // Insert your custom endpoint.
    $items[ self::$endpoint ] = __( 'Your Item Name', 'woocommerce' );
    // Insert back the logout item.
    $items['customer-logout'] = $logout;
    return $items;
}
/**
 * Endpoint HTML content.
 */
public function endpoint_content() {
    //example include('woocommerce/myaccount/Your-File.php');
    include('Path-To-Your-File.php');
}
/**
 * Plugin install action.
 * Flush rewrite rules to make our custom endpoint available.
 */
public static function install() {
    flush_rewrite_rules();
}
}
new My_Custom_My_Account_Endpoint();
// Flush rewrite rules on plugin activation.
register_activation_hook( __FILE__, array( 'My_Custom_My_Account_Endpoint', 'install' ) );

Вам нужно просто установить «Ваша желаемая ссылка» x1 и «Имя вашего элемента» x2 и «Путь к вашему файлу.php» x1 в этом источнике.
Если вы не знаете, где находится функция вашей темы. php:

1. Войдите в интерфейс администратора WordPress
2. На левой боковой панели наведите указатель мыши на Внешний вид, затем нажмите Редактор тем
3. На правой боковой панели нажмите functions.php

person Alireza Sabahi    schedule 11.10.2019