0

I'm trying to dynamically create widgets based on a posts from a post type. The code is as below. This function is pulled from my plugin class:

public function initWidgets() {

        // Config Widgets
        $args = array(
            'post_type' => 'my_post_type',
            'posts_per_page' => -1
        );

        $wp_query = new WP_Query( $args );

        while ( $wp_query->have_posts() ) { 
            $wp_query->the_post();

            $widget_id = 'wp_as_'.get_the_ID();
            $widget_title = get_the_title();
            $widget_desc = get_the_title();
            var_dump($widget_id);
            wp_register_sidebar_widget(
                $widget_id,
                $widget_title,
                array($this, 'widgetDislay'),
                array('description' => $widget_desc)
            );
        }
    }

    public function widgetDislay($args) {
        // Widget display code
    }

This though only works once, even though its in the loop only one widget appears in the back end. Is there a reason for this? Or is there an alternative way of achieving what I'm trying here? I've seen people using eval() to dynamically add widgets, though I'd rather steer clear of this approach if at all possible.

5
  • This looks like a very messy way to do this. Why not create one widget with a dropdown that allows the user to select a post from your post type?
    – s_ha_dum
    Mar 7, 2014 at 17:12
  • That actually sounds a much better way of doing it. Currently though when I drag the widget I created, it doesn't remain in the Available Widgets section. This will change though I imagine if I switch to using the WP_Widget class method?
    – thebluefox
    Mar 7, 2014 at 17:35
  • 1
    Yes, you must, must, must use the Widget API.
    – s_ha_dum
    Mar 7, 2014 at 17:37
  • I'll give that a go, thats for your help!
    – thebluefox
    Mar 7, 2014 at 17:37
  • If you have trouble, edit this question with the modified code and alter the description and someone should be able to help you.
    – s_ha_dum
    Mar 7, 2014 at 17:48

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.