Как включить файлы шаблонов в плагин WordPress? - PullRequest
0 голосов
/ 07 марта 2020

Я пытаюсь включить файлы шаблонов страниц в свой плагин WordPress для отображения пользовательского типа поста 'job' во внешнем интерфейсе.

Проблема: шаблоны загружаются правильно на одной странице пользовательского Тип сообщения, но остальные страницы пустые (на них ничего не отображается, кроме белой пустой страницы), включая домашнюю страницу, сообщение wp по умолчанию и страницу wp по умолчанию.

Подскажите, пожалуйста, мою ошибку и как ее решить? Спасибо.

Вот код:

function dwwp_load_templates( $original_template ) {

    if ( get_query_var( 'post_type' ) !== 'job' ) {
        return;
    }


    if ( is_archive() || is_search() ) {
        if( file_exists( get_stylesheet_directory().'/archive-job.php' ) ){
            return get_stylesheet_directory().'/archive-job.php';
        }else{
            return plugin_dir_path( __FILE__ ).'templates/archive-job.php';
        }
    } elseif( is_singular('job') ) {
        if( file_exists( get_stylesheet_directory().'/single-job.php' ) ){
            return get_stylesheet_directory().'/single-job.php';
        }else{
            return plugin_dir_path( __FILE__ ).'templates/single-job.php';
        }

    } else {
        return get_page_template();
    }
    return $original_template;

}
add_filter( 'template_include', 'dwwp_load_templates' );

Ответы [ 2 ]

1 голос
/ 07 марта 2020

Вы не можете просто сказать return. Вы должны вернуть шаблон. Исправить эту строку

if ( get_query_var( 'post_type' ) !== 'job' ) {
return $original_template;
} 
```
0 голосов
/ 07 марта 2020

Чтобы шаблоны работали, нам нужно уметь находить нужные шаблоны при их вызове. С помощью следующего кода плагин сначала ищет вызываемый файл шаблона в themes/your-theme/woocommerce-plugin-templates/{template-name}, если он не найден, он выполняет поиск в вашем основном файле темы themes/your-theme/{template-name} и возвращается к исходным шаблонам плагина в plugins/woocommerce-plugin-templates/templates/{template-name}.

<?php
/**
 * Locate template.
 *
 * Locate the called template.
 * Search Order:
 * 1. /themes/theme/woocommerce-plugin-templates/$template_name
 * 2. /themes/theme/$template_name
 * 3. /plugins/woocommerce-plugin-templates/templates/$template_name.
 *
 * @since 1.0.0
 *
 * @param   string  $template_name          Template to load.
 * @param   string  $string $template_path  Path to templates.
 * @param   string  $default_path           Default path to template files.
 * @return  string                          Path to the template file.
 */
function wcpt_locate_template( $template_name, $template_path = '', $default_path = '' ) {

    // Set variable to search in woocommerce-plugin-templates folder of theme.
    if ( ! $template_path ) :
        $template_path = 'woocommerce-plugin-templates/';
    endif;

    // Set default plugin templates path.
    if ( ! $default_path ) :
        $default_path = plugin_dir_path( __FILE__ ) . 'templates/'; // Path to the template folder
    endif;

    // Search template file in theme folder.
    $template = locate_template( array(
        $template_path . $template_name,
        $template_name
    ) );

    // Get plugins template file.
    if ( ! $template ) :
        $template = $default_path . $template_name;
    endif;

    return apply_filters( 'wcpt_locate_template', $template, $template_name, $template_path, $default_path );

}

Приведенный выше код находит и возвращает путь к существующему и действительному пути, который можно загрузить и включить на странице. Для того, чтобы фактически получить файл шаблона, есть дополнительная функция. Следующий код можно использовать непосредственно в функции шорткода для загрузки файлов.

<?php
/**
 * Get template.
 *
 * Search for the template and include the file.
 *
 * @since 1.0.0
 *
 * @see wcpt_locate_template()
 *
 * @param string    $template_name          Template to load.
 * @param array     $args                   Args passed for the template file.
 * @param string    $string $template_path  Path to templates.
 * @param string    $default_path           Default path to template files.
 */
function wcpt_get_template( $template_name, $args = array(), $tempate_path = '', $default_path = '' ) {

    if ( is_array( $args ) && isset( $args ) ) :
        extract( $args );
    endif;

    $template_file = wcpt_locate_template( $template_name, $tempate_path, $default_path );

    if ( ! file_exists( $template_file ) ) :
        _doing_it_wrong( __FUNCTION__, sprintf( '<code>%s</code> does not exist.', $template_file ), '1.0.0' );
        return;
    endif;

    include $template_file;

}

Этот код будет использовать функцию wcpt_locate_template() для поиска и возврата пути к допустимому файлу шаблона, когда нет действительного шаблона файл найден, и файл шаблона не существует в папке шаблонов плагинов, что никогда не должно происходить, будет отображаться ошибка.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...