0

I read that get_template_part() should only used by themes not plugins, I don't know if using it inside a widget function (created by the theme) is considered as a plugin or not.

Anyway, I'm trying to pass that widget variables ($myvar) to the template ('loop.php' in my case), but it doesn't fetch it even with using global $myvar; inside the template.

Here's my widget function code:

function widget($args, $instance) {
    extract( $args );
    $title = apply_filters('widget_title', $instance['title']);
    echo $before_widget;
    if ($title) { echo $before_title.$title.$after_title; }
    $myvar = 'start';
    get_template_part('loop'); ?>
    echo $after_widget;
}

2 Answers 2

1

Indeed, get_template_part is meant to be used in themes only, though that would include widgets inside your theme. Looking at the source code of the function you'll see that the main reason for this is that get_template_part does some extra theme related stuff before it calls locate_template in a non-default way.

That said you should have no problem calling it from a widget, so the issue most likely is that your loop.php is not in the place where WP is looking for it.

Refer to this answer for passing a variable to a template.

0

You can use set_query_var('myvarname', $myvarvalue); before get_template_part(). Then in your loop template you can access the var using $myvarname.

You can also skip all that and use locate template instead.

1
  • Doesn't work even outside the widget (in archive.php, for example).
    – Ahmed Saad
    Commented Jun 30, 2015 at 23:00

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.