0

i want to register new templates through my plugin. Now if i execute my functions to add the new templates i get the error message Too few arguments to function register_plugin_templates(), 1 passed in .../current/web/wp/wp-includes/class-wp-hook.php on line 309 and exactly 3 expected.

It looks like a wordpress error or did i something wrong?

This is my code:

functions.php

/** Template-Funktionen */
function get_plugin_templates(){
    $templates = [];
    $templates['dashboard'] = 'Dashboard Center';
    $templates['mein_account'] = 'Center - Mein Account';

    return $templates;
}

function register_plugin_templates( $page_templates, $theme, $post ){
    $plugin_templates = get_plugin_templates();

    foreach( $plugin_templates as $key => $value){
        $page_templates[$key] = $value;
    }

    return $page_templates;
}

function include_plugin_templates($template){
    global $post;

    $page_template_slug = get_page_template_slug( $post->ID );
    $plugin_templates = get_plugin_templates();

    if( isset( $plugin_templates[$page_template_slug] ) ){
        $template = plugin_dir_path( __DIR__ ) . '/templates/' . $page_template_slug . '.php';
    }

    return $template;
}

center.php

add_filter( 'theme_page_templates', __NAMESPACE__ . '\register_plugin_templates' );
add_filter( 'template_include', __NAMESPACE__ . '\include_plugin_templates' );

1 Answer 1

1

This is the problem, or rather what is missing from it:

add_filter( 'theme_page_templates', __NAMESPACE__ . '\register_plugin_templates' );

Specifically, you never told it that your function can accept 3 parameters, so it assumed it only accepts 1 as that's the absolute minimum needed for a filter to work. Then on top of that, none of your parameters are optional, they're required/mandatory. So PHP doesn't know what to do and generates an error.

Think of it this way:

If you were at a safe/vault and was told that to unlock it you had to place all 3 hands in the slots provided, what would you do? Most people have 2 hands, and others fewer, and you can't use somebody elses hand, so what are you supposed to do? It needs 3!

The official docs cover what parameters add_filter takes and what they do:

add_filter( string $hook_name, callable $callback, int $priority = 10, int $accepted_args = 1 ): true

Your code only provides the first 2, and doesn't define the priority or accepted arguments number.

https://developer.wordpress.org/reference/functions/add_filter/

2
  • Hey Tom, i understand. I hadn't seen it. Thank you.
    – Stefan
    Nov 28, 2022 at 13:36
  • if this answers your question, please consider marking it as the correct answer by clicking the tick button underneath the voting controls
    – Tom J Nowell
    Nov 28, 2022 at 15:22

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.