Create custom API endpoint to change custom header image

My goal is to create a custom API endpoint that I can call with an API call that changes the custom header image in Wordpress to another image (which would be passed along the API call, or maybe just switch to another media file in Wordpress, or similar).

UPDATE: I have now found the set_theme_mod() function which seems to be what I'm looking for, but when I tried to implement it I couldn't quite get it to work. The API call seems to be setup correctly because when I call it, the current header image dissappears. The problem is though that the new image does not get set.

Big thanks in advance.

function cs_set_logo() {
    set_theme_mod('header_image', $_POST['http://sprinth.xyz/britetest/wp-content/uploads/sites/2/2020/05/Universe-logo-test.png']);
    return;
}

add_action('rest_api_init', function() {
    register_rest_route('cs/v1', 'changelogo', [
        'methods' = 'POST',
        'callback' = 'cs_set_logo'
    ]);

});

Topic custom-header header-image functions php api Wordpress

Category Web


The header image falls under what WordPress calls theme modification values. To update that type of value, use the function set_theme_mod()

function cs_set_logo($request) {
 set_theme_mod('header_image', $request->get_param('new_header_image'));
 return new WP_REST_Response(null, 200);
}

add_action('rest_api_init', function() {
  register_rest_route('cs/v1', 'changelogo', [
  'methods' => 'POST',
  'callback' => 'cs_set_logo'
  ])
});

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.