Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix call_user_func_array() expects parameter 1 to be a valid callback, function 'my_cpt_single_template' in WordPress

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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' );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading