Having the system change the template for the post based on Category

Posted in: Newspaper
Post count: 1

I am trying to write logic in the functions.php to check the slug of my categories and if is category A then it updates the template, category B then its a different template on the post. It seems to be changing this via the metadata but not actually reflecting.

Anyone have any idea why it would update in the meta but not reflect? This was the code I was using:

add_action('save_post', function($post_id) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
if (wp_is_post_revision($post_id)) return;
if (get_post_type($post_id) !== 'post') return;

$categories = get_the_category($post_id);
if (empty($categories)) return;

$category_slugs = wp_list_pluck($categories, 'slug');

$template_map = [
'slugA' => 'tdb_template_1010',
'slugB' => 'tdb_template_1009',
'slugC' => 'tdb_template_1010',
];

$selected_template = 'tdb_template_919'; // Default template

foreach ($template_map as $slug => $template) {
if (in_array($slug, $category_slugs)) {
$selected_template = $template;
break;
}
}

// Always update base template
update_post_meta($post_id, 'td_post_template', $selected_template);

// Pull existing theme settings (or create new)
$theme_settings = get_post_meta($post_id, 'td_post_theme_settings', true);
if (!is_array($theme_settings)) {
$theme_settings = [];
}

// Inject template assignment into theme settings
$theme_settings['td_post_template'] = $selected_template;

// Save updated array
update_post_meta($post_id, 'td_post_theme_settings', $theme_settings);
});

Post count: 35449

Hi,
There is no need to create this kind of function because the Newspaper theme already has this option. All that you need to do is to have the single post templates you want to apply on your articles based on categories, then from the theme panel, you can set on each category the post category you want to apply – https://i.imgur.com/DzvlVQ3.png
Thank you!

Viewing 2 posts - 1 through 2 (of 2 total)
The forum ‘Newspaper’ is closed to new topics and replies.