Skip to content

Instantly share code, notes, and snippets.

@ccurtin
Last active October 7, 2016 18:03
Show Gist options
  • Save ccurtin/5a145dc018ecc1a1f80f to your computer and use it in GitHub Desktop.
Save ccurtin/5a145dc018ecc1a1f80f to your computer and use it in GitHub Desktop.
Wordpress: Generate Unique Widget for All/Any Pages/Posts
<?php
/**
* Registers a unique widget for each individual page
* @author christopher james curtin <git@christopherjamescurtin.com>
*/
//If dynamic sidebar exists
if (function_exists('register_sidebar')) {
$pages = get_pages( // First, retreive all pages that exist.
array (
'parent' => 0, // replaces 'depth' => 1
'exclude' => '' // exclude certain pages if needed (by ID)
)
);
$post_names = wp_list_pluck($pages,'post_name'); // plucks out a specific field(the slug) from an object(the pages)
foreach( $post_names as $post_name ) {
register_sidebar(array(
'name' => __(ucwords(str_replace('-',' ',$post_name)), 'THEME_NAME'), // Removes hyphens and capitalizes words
'description' => __('This is an optional page-specific widget', 'THEME_NAME'),
'id' => 'widget-area-'.$post_name,
'before_widget' => '<div class="widget-area-'.$post_name.' widget-area-unique-all">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>'
));
}
}
?>
<?php
/**
* First gets the slug of the current page, then creates a unique widget based on that slug name
*/
function get_widget($post_name=null){
global $post;
if($post_name == null){$post_name = get_post( $post )->post_name;} else {
$post_name = $post_name;
}
if(!function_exists('dynamic_sidebar') || !dynamic_sidebar('widget-area-'.$post_name));
}
?>
<?php
/**
* Use snippets like this inside of a template file to display a widget.
*/
if (is_page()) { // can also change/duplicate to create unique widgets for certain pages, posts, etc. EX: if(is_post('slug-name')...)
get_widget(); //will display a unique widget based on the slug name.
}
// TODO: edit get-widget() to find whether the user wants to create a Class or an ID for the widget. (find the first character entered "." or "#")
if (is_single()) { // can also change/duplicate to create unique widgets for certain pages, posts, etc. EX: if(is_post('slug-name')...)
get_widget("single-blog-posts-pages"); // Will display widget with ID of "widget-area-single-blog-posts-pages" on all Single Blog Posts Pages
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment