Переопределение шаблона с использованием раздела настройки

Я пытаюсь переопределить свои шаблоны по умолчанию из раздела настройки, я использую код для этого, но если я его использую, я не могу назначить шаблон странице редактирования страницы. Может ли кто-нибудь дать представление о том, как оба раздел настройки и редактирование шаблона редактирования страницы. Я хочу установить шаблон, когда создаю страницу, и после ее назначения я хочу переопределить. У меня есть страница блога, я хочу назначить его archive.php, а десять - переопределить его из раздела настройки. Есть особое условие, в котором я хочу, чтобы он работал.

 <?php
    /**
     * Adds the Customize page to Select template For Pages
     */

    add_action( 'wp_footer', 'cur_page_template' );
function cur_page_template(){
    var_dump( get_option('current_page_template') );
    var_dump( get_page_template() );
    exit;
}
 function widgetsite_template_override($wp_customize){
    $wp_customize->add_panel( 'template_options', array(
        'title' => __( 'Template Options', 'widgetsite' ),
        'description' => $description, // Include html tags such as <p>.
        'priority' => 160, // Mixed with top-level-section hierarchy.
    ) );

    $wp_customize->add_section('theme_template_override', array(
        'title'    => __('Override  Templates', 'widgetsite'),
        'panel' => 'template_options',
        'description' => '',
        'priority' => 120,
    ));


    $templates = get_page_templates();

    $cats = array();
    $i = 0;
    foreach($templates as $template_name => $template_file){
        //$cats[$template_name] = $template_name;   
        if (strpos($template_file,'layouts') !== false) {
            $cats[$template_file] = $template_name;
        }
    }


    $wp_customize->add_setting('widgetsite_archive_template');
    $wp_customize->add_setting('widgetsite_page_template');
    $wp_customize->add_setting('widgetsite_index_template');
    $wp_customize->add_setting('widgetsite_post_template');
    $wp_customize->add_setting('widgetsite_search_template');

    $wp_customize->add_control( 'widgetsite_archive_template', array(
        'settings' => 'widgetsite_archive_template',
        'label'   => 'Override Archive Template:',
        'section'  => 'theme_template_override',
        'type'    => 'select',
        'choices' => array_merge(array( "archive.php"=>get_option('current_page_template')), $cats)
    ));
    $wp_customize->add_control( 'widgetsite_page_template', array(
        'settings' => 'widgetsite_page_template',
        'label'   => 'Override Page Template:',
        'section'  => 'theme_template_override',
        'type'    => 'select',
        'choices' => array_merge( array( "page.php" =>get_option('current_page_template')), $cats)
    ));
    $wp_customize->add_control( 'widgetsite_index_template', array(
        'settings' => 'widgetsite_index_template',
        'label'   => 'Override Index Template:',
        'section'  => 'theme_template_override',
        'type'    => 'select',
        'choices' => array_merge(array( "index.php"=>get_option('current_page_template')), $cats)
    ));
    $wp_customize->add_control( 'widgetsite_post_template', array(
        'settings' => 'widgetsite_post_template',
        'label'   => 'Override Post Template:',
        'section'  => 'theme_template_override',
        'type'    => 'select',
        'choices' => array_merge(array( "post.php"=>get_option('current_page_template')), $cats)
    ));
    $wp_customize->add_control( 'widgetsite_search_template', array(
        'settings' => 'widgetsite_search_template',
        'label'   => 'Override Search Template:',
        'section'  => 'theme_template_override',
        'type'    => 'select',
        'choices' => array_merge(array( "search.php"=>get_option('current_page_template')), $cats)
    ));

}
add_action('customize_register', 'widgetsite_template_override');

$theme_mode_templates['archive.php'] = get_theme_mod("widgetsite_archive_template");
$theme_mode_templates['page.php'] = get_theme_mod("widgetsite_page_template");
$theme_mode_templates['index.php'] = get_theme_mod("widgetsite_index_template");
$theme_mode_templates['post.php'] = get_theme_mod("widgetsite_post_template");
$theme_mode_templates['search.php'] = get_theme_mod("widgetsite_search_template");


function widgetsite_template_redirect($template){

    global $wp_query;
    global $post;
    $cur= basename($template);
    if(  $cur === 'page.php' && get_theme_mod("widgetsite_page_template")){  //note $cur will never be empty!
        $template=  get_template_directory() . '/' . get_theme_mod("widgetsite_page_template");// assuming this will return correct template...
        //if issues try hardcoding a path to test...
    }
    if(  $cur === 'archive.php' && get_theme_mod("widgetsite_archive_template")){  //note $cur will never be empty!
        $template=  get_template_directory() . '/' . get_theme_mod("widgetsite_archive_template");// assuming this will return correct template...
        //if issues try hardcoding a path to test...
    }
    if(  $cur === 'index.php' && get_theme_mod("widgetsite_index_template")){  //note $cur will never be empty!
        $template=  get_template_directory() . '/' . get_theme_mod("widgetsite_index_template");// assuming this will return correct template...
        //if issues try hardcoding a path to test...
    }
    if(  $cur === 'post.php' && get_theme_mod("widgetsite_post_template")){  //note $cur will never be empty!
        $template=  get_template_directory() . '/' . get_theme_mod("widgetsite_post_template");// assuming this will return correct template...
        //if issues try hardcoding a path to test...
    }
    if(  $cur === 'search.php' && get_theme_mod("widgetsite_search_template")){  //note $cur will never be empty!
        $template=  get_template_directory() . '/' . get_theme_mod("widgetsite_search_template");// assuming this will return correct template...
        //if issues try hardcoding a path to test...
    }
    return $template;


}
add_filter( 'template_include', 'widgetsite_template_redirect', 99 ); 

Ответы

Ответ 1

  • Как поле выбора шаблона работает с экрана редактирования сообщений.

Важно помнить, что страницы также являются сообщениями, а все мета-сообщения, относящиеся к сообщениям, хранятся в метатеге сообщений. Тип публикации страницы несколько отличается от стандартных типов сообщений, поскольку они не соответствуют функции использования шаблона single-postname.php. Вместо этого страницы сохраняют путь к файлу шаблона в таблице базы данных wp_postmeta с ключом _wp_page_template.

Таким образом, один из вариантов изменения этого значения - изменить его после сохранения сообщения.

function save_template_file( $post_id ) {

    if ( 'page' != $post->post_type ) {
        return;
    }

    //insert logic here
    $filelocation= 'anywhere.....';

    update_post_meta($post_id, '_wp_page_template', $filelocation);

}

add_action('save_post', 'save_template_file', 11 );

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

  1. Фильтр template_include находится в пределах функции, которая ищет правильный шаблон для типа post pages (другие типы сообщений имеют фильтр single_template)

Ваше использование include здесь неверно. Не забывайте, что фильтр ожидает, что значение вернется, чтобы работать корректно в этом случае $template.

Итак, если мы хотим изменить шаблон для страниц....

add_filter('template_include', 'assign_new_template');

function assign_new_template ($template){

 //we already have a template name, no need to pull it again..
 $cur= basename($template);

 if(  $cur === 'page.php' && get_theme_mod("widgetsite_page_template")){  //note $cur will never be empty!
    $template=  get_template_directory() . '/layouts/' . get_theme_mod("widgetsite_page_template");// assuming this will return correct template...
    //if issues try hardcoding a path to test...
 }

// dont need a else, we will only change the template if our logic is satisfied...

// etc

return $template;
}
  1. Настройка выбора

У вас отсутствует значение по умолчанию, поэтому я предлагаю следующий мод, так как я не вижу, что ваш параметр в get_option('current_page_template'), но если есть правильное имя файла, замените его page.php.

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

$wp_customize->add_control( 'widgetsite_search_template', array(
    'settings' => 'widgetsite_search_template',
    'label'   => 'Override Search Template:',
    'section'  => 'theme_template_override',
    'type'    => 'select',
    'choices' => array_merge(array("page.php"=>'default'), $cats)
 ));

Если вы сохраняете все параметры, как указано выше, он должен работать (это было для меня)!