Is it possible to call instance methods of a class from a template file that is loaded by that class? If I try to invoke $this from the template, I get Fatal error: Using $this when not in object context and invoking everything statically defeats the purpose of classes.

In other words, is it possible to get the template file below to call a public method in instance of a WP_Widget subclass the same way I can call the_title()?


<?php get_header(); ?>
<main id="main" class="site-main" role="main">
        <p><?php callSomeClassMethodHere() ?></p>
<?php get_footer(); ?>



Plugin Name: My Custom Plugin
Description: This is a test plugin
Version: 0.0.1

class CustomPlugin extends \WP_Widget {
    public function __construct() {
            'CustomPlugin', // ID
            __('Custom Plugin', 'text_domain'), // Name
            array( 'description' => __( 'This is a custom plugin', 'text_domain' )) // Description

        add_action('init', array($this, 'init'), 10, 0);
        add_filter('query_vars', array($this, 'query_vars'));
        add_action('page_template', array($this, 'page_template'));

    public function init() {


    public function query_vars($query_vars) {
        $query_vars[] = 'custom_id';

        return $query_vars;

    public function page_template($path = '') {
        $path = dirname(__FILE__) . '/CustomPluginTemplate.php';

        return $path;

add_action('widgets_init', function () { register_widget('CustomPlugin'); });

1 Answer 1


You can just instantiate an object from class CustomPlugin like $obj = new CustomPlugin('id','name','desc'); in CustomPluginTemplate.php

and call any method from the class within the CustomPluginTemplate.php file as $obj->query_vars();

Before instantiating make sure you class is included.

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.