7
votes

I need to display my custom made widget in WP page based custom page template programmatically.

This is the scenario:

I created page based on custom page template called "product" now I need in its sidebar display my custom made widget. I need this side bar to be totally different from other pages this is why I want to display it programmatically. I tried to use the_widget() function but I think it works only with built in widgets and also I don't know how to pass parameters registered with register_sidebar function to it, because it seems it doesn't use them by default.

Actually I used this : the_widget('WP_Widget_Search') to test it and widget was there but it ignored theme settings, I mean settings in function.php :

register_sidebar( array(
    'name' => 'Sidebar',
    'before_widget' => '<div id="%1$s" class="widget %2$s">',
    'after_widget' => '</div></div>',
    'before_title' => '<h3>',
    'after_title' => '</h3><div class="padder">'
) );

So as I said I don't know if it works with custom made widgets (created in plugins) because I don't know how to pass widget name there and params. How to do that?

4

4 Answers

10
votes

Dynamically create a dynamic instance of the widget using the_widget(), eg:

<div id="xxx" class="widget-area" role="complementary">
    <div id="sidebar-dyn">
        <?php the_widget( 'WP_Widget_Recent_Posts' ); ?>
    </div>
</div>
1
votes

Why the need to include custom widget programatically. I mean you can simply create another sidebar that is shown only on your custom page template "product"

Further as you need to do it for your custom page, you don't even need to check for any condition. Simply put this code in your "prdouct" page template file anywhere ( where you would like to display your sidebar".

<?php if (function_exists('dynamic_sidebar') && dynamic_sidebar('Product Sidebar')) ;?>

And simply drag your widget to this sidebar from admin panel.

1
votes

If the widget has a shortcode, call it using this:

<?php echo do_shortcode( $content ) ?>
0
votes

you're question isn't exactly clear to me, but what i am gathering is that 1. you need to register your widget and 2. you need for it to ONLY show on the product page.

to register, place this in functions.php (you may already have the first line in your functions file):

<?php
if ( function_exists('register_sidebar') )
register_sidebar(array(
'name'=> 'Product Sidebar',
'before_widget' => '<div id="%1$s" class="widget %2$s">',
'after_widget' => '</div></div>',
'before_title' => '<h3>',
'after_title' => '</h3><div class="padder">'
));
?>

this would be the code to include in sidebar.php to display the above only on the page called "Product".

<?php if (is_page('Product')) ;?>
<?php if (function_exists('dynamic_sidebar') && dynamic_sidebar('Product Sidebar')) ;?>
<?php endif; ?>