I managed to solve this myself. Instead of using register_sidebars()
to register the sidebars all together, I simply used the singular register_sidebar()
in a for loop, so that it registered a sidebar for every matching page.
All one would need to do to get this working is change the template name (in my case template-generic-sidebar
) to their own template slug/name and place this code in functions.php
$get_pages_args = array(
'post_type' => 'page',
'post_status' => 'publish'
);
$all_pages = get_pages($get_pages_args);
$counter = 0;
$sidebars_required = array();
foreach($all_pages as $page){
$page_id = $page->ID;
$page_template = get_page_template_slug($page_id);
if (strpos($page_template,'template-generic-sidebar') !== false) {
$counter++;
$page_details = array(
"title" => $page->post_title,
"slug" => $page->post_name,
);
array_push($sidebars_required,$page_details);
}
}
for ($i = 1; $i <= $counter; $i++) {
$array_counter = $i-1;
$args = array(
'name' => __($sidebars_required[$array_counter]['title'].' sidebar'),
'id' => 'sidebar-'.$sidebars_required[$array_counter]['slug'],
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>'
);
register_sidebar($args);
}