T
T
teodor7teodor72016-04-06 11:32:23
WordPress
teodor7teodor7, 2016-04-06 11:32:23

How to make a template for posts of a certain category in wordpress?

How to make a template for single posts of a certain category in wordpress? That is, so that posts in different categories have a different template.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Dvoryanov, 2016-04-06
@Raxen

In function.php add -

// Шаблон родительской категории для дочерних
add_action('template_redirect', 'wpds_parent_category_template');
function wpds_parent_category_template()
{
    if (!is_category())
        return true; 

    // получаем объект текущей рубрики
    $cat = get_category(get_query_var('cat'));
    
    while ($cat && !is_wp_error($cat)) {
        $template = get_template_directory() . "/category-{$cat->slug}.php";
        // загружаем, если файл шаблона существует.
        if (file_exists($template)) {
            load_template($template);
            exit;
        }

        $cat = $cat->parent ? get_category($cat->parent) : false;
    }
}

// Подключение шаблонов к постам 
if(!function_exists('get_post_templates')) {
function get_post_templates() {
    $templates = wp_get_theme()->get_files( 'php', 1 );
    $post_templates = array();

    $base = array(trailingslashit(get_template_directory()), trailingslashit(get_stylesheet_directory()));

    foreach ((array)$templates as $template) {
        $template = WP_CONTENT_DIR . str_replace(WP_CONTENT_DIR, '', $template); 
        $basename = str_replace($base, '', $template);

        if (false !== strpos($basename, '/'))
            continue;

        $template_data = implode('', file( $template ));

        $name = '';
        if (preg_match( '|Single Post Template:(.*)$|mi', $template_data, $name))
            $name = _cleanup_header_comment($name[1]);

        if (!empty($name)) {
            if(basename($template) != basename(__FILE__))
                $post_templates[trim($name)] = $basename;
        }
    }

    return $post_templates;
}}

Now you can create templates in categories according to the principle
category-{name}.php
When editing a post, you need to select the template of the desired category

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question