Sidebar wrapper for custom post types

I have a few custom post types registered in WP. I have modified single.php to use different content-single-custom_post.php templates like this:

<?php get_template_part('templates/content-single', get_post_type()); ?>

The loads content-single-custom_post.php in place of content-single.php.

I’m now trying to use a custom sidebar.php template for each custom post type. One method is to simply use conditionals within sidebar.php to display different content. That’s easy enough, but I’m trying to use the sidebar wrapper to separate into different files, without success.

If my custom post type is named “books”, I can customize the content by creating content-single-books.php. I thought I could also create sidebar-single-books.php as the related sidebar template, but that doesn’t seem to work. What am I missing?

The base and sidebar templates are chosen based on the template selected by the WordPress template hierarchy.

So if WordPress is loading single.php, Roots will first try to loadbase-single.php for the base template and templates/sidebar-single.php for the sidebar template.

You can override this by modifying the example I gave in the docs:

<?php
add_filter('roots/wrap_sidebar', 'roots_wrap_sidebar_cpts'); // Add our function to the roots/wrap_sidebar filter

function roots_wrap_sidebar_cpts($templates) {
  $cpt = get_post_type(); // Get the current post type
  
  if ($cpt) {
    array_unshift($templates, 'templates/sidebar-' . $cpt . '.php'); // Shift the template to the front of the array
  }

  return $templates; // Return our modified array with templates/sidebar-$cpt.php at the front of the queue
  }
?>

If you need more control over sidebar selection, then my wrapper override plugin may be helpful.