Home > front end >  How to fix call_user_func_array() expects parameter 1 to be a valid callback, function 'my_cpt_
How to fix call_user_func_array() expects parameter 1 to be a valid callback, function 'my_cpt_

Time:01-13

I am trying to run some jQuery inside a php custom post type template in WordPress using the hierarchy file: single-event.php file (coped fron single.php with jQuery added at top of template):

<script>
jQuery(document).ready(function($) {
    var hexColor = '<?php the_field("event_main_color") ?>';
    $(".event-box-background").css("background-color", hexColor);
    console.log('Working');
});
</script>  

The console does not log so the script isn't running when I load a single event page.

I have this code in my functions.php file:

function my_cpt_event_template($single_template) {
global $post;
if ($post->post_type == 'event') {
$single_template = dirname( __FILE__ ) . '/single-event.php';
}
return $single_template;
}

add_filter( 'single_template', 'my_cpt_single_template' );

And I receive this error when visiting a single custom post type:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'my_cpt_single_template' not found or invalid function name in /public_html/wp-includes/class-wp-hook.php on line 310

How can I fix this so WordPress loads single-event.php template file for the CPT UI generated custom post type 'event'?

Much appreciated.

CodePudding user response:

I think this error comes due to your function name being different.

You need to change the function name in the hook to match the one you defined.

function my_cpt_single_template( $single_template ) {
    global $post;
    if ( $post->post_type == 'book' ) {
        $single_template = dirname( __FILE__ ) . '/single-event.php';
    }
    return $single_template;
}
add_filter( 'single_template', 'my_cpt_single_template' );
  • Related