0

I use a theme which has a public static function to display a part of a page like:

trait SomeTrait {
    public static function some_function() {
    ?>
        <div class="some_class">Some content</div>
    <?
    }
}

and the helper file looks like:

class Helper {
    use SomeTrait;
    // ...
}

I need to override the function in my plugin.

In the plugin I try the code:

/*
Plugin Name: MyPlugin
Description: -
Version: 1.0
Author: -
*/

if ( ! defined( 'ABSPATH' ) ) exit;

class Extra extends Helper {
    trait SomeTrait{
        function some_function() {
            ?>
            <div>Test</div>
            <?php
        }
    }
}

But I receive the fatal error: Class 'Helper' not found in ...


UPDATE

If I try:

function my_function() {
    class Extra extends Helper {
        public static function some_function() {
            ?>
            <div>Test</div>
            <?php
        }
    }
}

add_action( 'init', 'my_function' ); // with the 'after_theme_setup' the result is the same

I don't receive any errors, but my function doesn't override the existing one

0

I believe plugins are loaded before the theme (see here "plugins_loaded" vs "setup_theme") so the error is occurring because Helper has not loaded yet.

One thing you can try is to create a child theme and add the class override there (via functions.php).

You can also provide your override after the theme has loaded by hooking into "after_theme_setup" or "init". There are more details in this post here: How to override a theme function (within a class) using a plugin

|improve this answer|||||
  • Thanks, I need only overriding by my plugin. See my update – stckvrw Jan 15 at 10:52
  • Can you post the full code you're trying to override in the theme? Also, wouldn't you need to call Extra->some_function(); in order for your override to execute? – Tom Jan 15 at 11:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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