我在一个网站上为一个特定的模板做了这个。具有该模板的任何页面都有自己的小部件区域,允许专门针对该页面的一个或多个小部件。有几个插件可以为您提供动态小部件逻辑,但这种方法更有针对性,可能适合您的问题(它在特定的网站上也有)。
对于管理员,小部件区域必须全部注册,以便您可以为这些页面分配和配置小部件:
// dynamically add some widget zones for pages using some templates
add_action(\'sidebar_admin_setup\', \'wpse_76601_actionSidebarAdminSetup\');
/**
* handle action sidebar_admin_setup to check for dynamically created sidebars
* and make sure they\'re registered
*/
function wpse_76601_actionSidebarAdminSetup() {
global $post;
global $wp_registered_sidebars;
// find all pages that use template with dynamic widget zone
$query = new WP_Query(array(
\'meta_key\' => \'_wp_page_template\',
\'meta_value\' => \'wpse-template-dept.php\',
\'post_type\' => \'page\',
\'nopaging\' => true,
\'orderby\' => \'title\',
\'order\' => \'ASC\',
));
while ($query->have_posts()) {
$query->the_post();
$id = "wpse-{$post->ID}-aside";
// register any that aren\'t already registered
if (!isset($wp_registered_sidebars[$id])) {
register_sidebar( array(
\'name\' => $post->post_title . \' Asides\',
\'id\' => $id,
\'description\' => \'Aside widgets for page \' . $post->post_title,
\'before_widget\' => \'<li id="%1$s" class="widget-container %2$s">\',
\'after_widget\' => \'</li>\',
\'before_title\' => \'<h3 class="widget-title">\',
\'after_title\' => \'</h3>\',
) );
}
}
wp_reset_postdata();
}
然后在页面模板中,小部件区域必须在调用之前再次注册;只需在调用之前在模板顶部添加
wp_head()
, 它将只注册该特定页面。
function template_widgetsInit() {
global $post;
register_sidebar( array(
\'name\' => $post->post_title . \' Asides\',
\'id\' => "wpse-{$post->ID}-aside",
\'description\' => "Aside widgets for page {$post->post_title}",
\'before_widget\' => \'<li id="%1$s" class="widget-container %2$s">\',
\'after_widget\' => \'</li>\',
\'before_title\' => \'<h3 class="widget-title">\',
\'after_title\' => \'</h3>\',
) );
}
template_widgetsInit();