2
votes

I'm trying to get wordpress to add a sidebar for each post of a custom post type. So when I go to the widgets area I want there to be as many sidebars as there are posts of the custom post type I named portfolio.

This is the code I'm using but I only get 1 sidebar that has no title.

UPDATE: I added the global $posts in the code and now I do get the sidebars, then I changed the_title() to get_the_title(). Now it's working. Full code below. If anyone has a better solution though please let me know.

function the_slug() {
    $post_data = get_post($post->ID, ARRAY_A);
    $slug = $post_data['post_name'];
    return $slug; 
}

add_action( 'init', 'portfolios_sidebars' );
/**
 * Create widgetized sidebars for each portfolio
 *
 * This function is attached to the 'init' action hook.
 */

function portfolios_sidebars() {
    $args = array( 'post_type' => 'portfolios', 'numberposts' => -1, 'post_status' => 'publish'); 
    $portfolios = get_posts( $args );
    global $post;
    if ($portfolios) {
        foreach ( $portfolios as $post ) {
            setup_postdata($post);
            $portfoliotitle = get_the_title();
            $portfolioslug = the_slug();
            register_sidebar( array(
                'name' => $portfoliotitle,
                'id' => $portfolioslug . '-sidebar',
                'description' => 'This is the ' . $portfoliotitle . ' widgetized area',
                'before_widget' => '<aside id="%1$s" class="widget %2$s" role="complementary">',
                'after_widget' => '</aside>',
                'before_title' => '<h4 class="widget-title">',
                'after_title' => '</h4>',
            ) );
        }
        wp_reset_postdata();
    }
}
1

1 Answers

0
votes

I would just remove unnecessary function calls:

add_action( 'init', 'portfolios_sidebars' );
/**
 * Create widgetized sidebars for each portfolio
 *
 * This function is attached to the 'init' action hook.
 */

function portfolios_sidebars() {
    $args = array( 'post_type' => 'portfolios', 'numberposts' => -1, 'post_status' => 'publish'); 
    $portfolios = get_posts( $args );
    if ($portfolios) {
        foreach ( $portfolios as $portfolio ) {
            $portfoliotitle = $portfolio->post_title;
            $portfolioslug = $portfolio->post_name;
            register_sidebar( array(
                'name' => $portfoliotitle,
                'id' => $portfolioslug . '-sidebar',
                'description' => 'This is the ' . $portfoliotitle . ' widgetized area',
                'before_widget' => '<aside id="%1$s" class="widget %2$s" role="complementary">',
                'after_widget' => '</aside>',
                'before_title' => '<h4 class="widget-title">',
                'after_title' => '</h4>',
            ) );
        }
    }
}