Wordpress Warning: call_user_func_array () expects parameter 1 to be a valid callback, the array must have exactly two members

I am trying to add a custom function that will add the Access-Control-Allow-Origin header as I cannot access the .conf files on the server.

my function:

add_filter( 'wp_headers', array( 'eg_send_cors_headers' ), 10, 1 );
function eg_send_cors_headers( $headers ) {

        $headers['Access-Control-Allow-Origin']= get_http_origin(); 
        $headers['Access-Control-Allow-Credentials'] = 'true';


        if ( 'OPTIONS' == $_SERVER['REQUEST_METHOD'] ) {

            if ( isset( $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] ) ) {
                $headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS';
            }

            if ( isset( $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] ) ) {
                $headers['Access-Control-Allow-Headers'] = $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'];
            }

        }

    return $headers;
}

      

Then I get this error on save:

Notice: Undefined offset: 1 in /example/wp-includes/plugin.php on line 873 Warning: call_user_func_array() expects parameter 1 to be a valid callback, array must have exactly two members in /example/wp-includes/plugin.php on line 192

      

I'm new to wordpress hooks and I'm not sure how to solve this.

+3


source to share


1 answer


Ok I figured it out. Hope this helps someone else.

Since I only call a function without a method, I just removed the array () around my function name in the add_filter function. As you can see in example # 1 here , if you only call the function with arguments, you only need to wrap your function name in single quotes.



the fixed code looks like this:

add_filter( 'wp_headers', 'eg_send_cors_headers', 10, 1 );
function eg_send_cors_headers( $headers ) {

        $headers['Access-Control-Allow-Origin']= get_http_origin(); 
        $headers['Access-Control-Allow-Credentials'] = 'true';


        if ( 'OPTIONS' == $_SERVER['REQUEST_METHOD'] ) {

            if ( isset( $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] ) ) {
                $headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS';
            }

            if ( isset( $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] ) ) {
                $headers['Access-Control-Allow-Headers'] = $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'];
            }

        }

    return $headers;
}

      

+6


source







All Articles