0
votes

i am using a wordpress plugin called "Wordpress Page Widgets". this widget allows me add widgets per page and display them via "dynamic_sidebar( 'sidebar' )" within my templates.

as i would like to have full control of every page on my website including the archive pages, i have created every page instance in the pages area including the page where the archive page will sit and just load the content by page id where the slug name matches.

function theme_page_id_by_slug(){
    global $post;
    $post_type = $_GET['post_type'] ? $_GET['post_type'] : get_post_type($post->ID);
    $post = get_post(get_page_by_path(str_replace(get_home_url().'/','',get_post_type_archive_link($post_type))));
    return $post;
}

this approach has worked a treat for almost every instances where i can actually get the content or post_meta via the page id. however the sidebar does not accept any page id parameters. therefore i am having to write a function so it can display widgets by a page id.

function theme_sidebar(){
    $post = theme_page_id_by_slug();
    $sidebar = get_post_meta($post->ID, '_sidebars_widgets', true);

    foreach($sidebar['sidebar'] as $k => $v){
        $v = explode('-',$v);
        array_pop($v);
        foreach($v as $k2 => $v2){
            the_widget('WP_Widget_'.ucfirst($v2));
        }
    }
}

the "Wordpress Page Widgets" plugin stores the widget id base in a post_meta which is fine, but "the_widget" uses the the widget class name as a parameter which is not reliable as not every widget that i have come across begin with "WP_Widget_".

i thought of using the "global $wp_widget_factory" to list all widgets and then filter the results against the post_meta.

can anyone point me to the right direction?

1

1 Answers

0
votes

i have modified my original theme_sidebar function so it uses the global $wp_widget_factory

function theme_sidebar(){
    global $wp_widget_factory;

    foreach($wp_widget_factory->widgets as $k => $v){
        $widgets[$v->id_base] = $k;
    }

    if(is_single()){
        global $post;
    }else{
        $post = theme_page_id_by_slug();
    }

    $sidebar = get_post_meta($post->ID, '_sidebars_widgets', true);

    foreach($sidebar['sidebar'] as $k => $v){
        $v = explode('-',$v);
        array_pop($v);
        $v = implode('-',$v);
        if(isset($widgets[$v])){
            the_widget($widgets[$v]);
        }
    }
}

function theme_page_id_by_slug(){
    global $post;
    $post_type = $_GET['post_type'] ? $_GET['post_type'] : get_post_type($post->ID);
    $url = str_replace(get_home_url().'/','',get_post_type_archive_link($post_type));
    $page = get_post(get_page_by_path($url));
    return $page;
}