• Hi,

    I’m creating a classic WordPress theme. I’d like to create a configuration class with a plugin_setup method that handles various configurations, such as importing CSS and JavaScript, creating custom post types and taxonomies, and other tasks.

    I’ve created a simple setup that currently does nothing, but when I load a basic empty homepage.php page, the plugin_setup method is called twice. Is it possible to prevent the plugin_setup method from being called twice?

    This is the code I’m using:

    Code of functions.php:

    if ( ! class_exists( 'DIS_ThemeManager' ) ) {
    require_once get_template_directory() . '/classes/theme-manager.php';
    }
    if ( class_exists( 'DIS_ThemeManager' ) ) {
    error_log("Running after_setup_theme");
    add_action(
    'after_setup_theme',
    function() {
    $theme_manager = DIS_ThemeManager::get_instance();
    $theme_manager->plugin_setup();
    }
    );
    }

    Code of theme-manager.php :

    class DIS_ThemeManager {
    protected static $instance = null;


    private function __construct() {}

    public static function get_instance() {
    if ( is_null( self::$instance ) ) {
    self::$instance = new self();
    }
    return self::$instance;
    }

    public function plugin_setup() {
    }
    }

    Code of homepage.php:

    <?php
    // get_header();
    ?>
    <main id="main-container" class="main-container redbrown" role="main">
    HELLO
    </main>

    With this setup, the add_action method and plugin_setup are called twice.

    If I uncomment get_header() in homepage.php, they are called three times.

    Why does this happen? Is it possible to prevent this behavior?

    Thank you

    Claudio

Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    There are numerous hooks that fire more than once for no apparent reason. I cannot explain why, but it’s something we must cope with. Many callbacks are of no consequence if they execute multiple times. For those where there are consequences, callbacks can remove themselves from the call stack so they only execute once per request. Use remove_action() or remove_filter() as appropriate.

    While it may seem like removal should happen as the last thing in a callback, this can create a race condition. It’s better to do removal first thing. The callback will still complete its remaining tasks.

Viewing 1 replies (of 1 total)

The topic ‘How to setup correctly a custom classic theme?’ is closed to new replies.