I am attempting to dynamically register sidebars for certain pages. The pages must meet the following criteria:
- be published
- be a page (not a post)
- use the template 'template-generic-sidebar'
In my functions.php I have created a short script using get_pages()
which get a list of all pages. It counts how many of these pages match the above criteria, and stores the information required about them in an array called $sidebars_required
:
$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(
"ID" => $page_id,
"title" => $page->post_title,
"slug" => $page->post_name,
);
array_push($sidebars_required,$page_details);
}
}
In my test case the required number of sidebars stored in $counter
= 3
.
In my test case $sidebars_required
look like this:
array(3) {
[0]=>
array(3) {
["ID"]=>
int(27)
["title"]=>
string(8) "About Us"
["slug"]=>
string(8) "about-us"
}
[1]=>
array(3) {
["ID"]=>
int(13)
["title"]=>
string(20) "Generic Page Example"
["slug"]=>
string(20) "generic-page-example"
}
[2]=>
array(3) {
["ID"]=>
int(15)
["title"]=>
string(9) "Resources"
["slug"]=>
string(9) "resources"
}
}
But I am stuck with registering the correct number of sidebars each with different name, as I don't know how to correctly loop through my array to create the list of $args
required for register_sidebar()
I already have $counter
ready to specify the number
required by register_sidebars()
:
register_sidebars($counter);
But how can I create my $args
using the page_name
from my array? How do I loop through this array, but use it to fill in the $args
for register_sidebars()
I am confused as to how register_sidebars
allows for multiple sidebars to be registered when it doesn't allow for multiple lists of arguments to be included.
I envision something like this:
$args = array(
'name' => __($sidebars_required[0]['title'].'sidebar'),
'id' => 'sidebar-'.$sidebars_required[0][slug],
'before_widget' => '<li id="%1$s" class="widget %2$s">',
'after_widget' => '</li>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>'
);
So in the above, the name of the sidebar would be e.g About Us Sidebar
and it's ID would be sidebar-about-us
But obviously because there is only one $args
list, there is no way to correctly register this for 3 different sidebars with different names. I am only able to create three identical sidebars.