How to override theme's public static function inside of a trait?

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() {
            ?
            divTest/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() {
            ?
            divTest/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

Topic functions php plugin-development themes Wordpress

Category Web


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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.