Custom Background by Page IDs

I use TwentyTwent theme and want to change its background colour by page IDs.

I'm not sure but when I check the functions.php, I see below lines which are related to background colours:

    // Custom background color.
    add_theme_support(
        'custom-background',
        array(
            'default-color' = 'f5efe0',
        )
    );

    // Add the background option.
    $background_color = get_theme_mod( 'background_color' );
    if ( ! $background_color ) {
        $background_color_arr = get_theme_support( 'custom-background' );
        $background_color     = $background_color_arr[0]['default-color'];
    }
    $editor_color_palette[] = array(
        'name'  = __( 'Background Color', 'twentytwenty' ),
        'slug'  = 'background',
        'color' = '#' . $background_color,
    );

Is there any simple way to change the background colour according to Page's ID?

Regards.

Topic child-theme custom-background php css customization Wordpress

Category Web


Not the most elegant solution, but you can use something like this

add_action('wp_footer', function() {
    $post = get_post();
    if ($post && $post->ID == ... do your post selection here) {
        ?>
        <style>
        body {
            background-color: #fff !important;
        }
        </style>
        <?php

    }
});

The CSS is generated on the file inc/custom-css.php, the background color is set on line 76:

$background = sanitize_hex_color_no_hash( get_theme_mod( 'background_color' ) );

So you can take advantage of the theme_mod_{$name} filter, which changes the value of the get_theme_mod($name) function, by adding this to your functions.php file:

add_filter(
    'theme_mod_background_color',
    function( $value ) {
        $custom_bg_page_ids = array( 18, 19, 20 );
        $custom_bg_color = 'ca2d2d';
        global $post;
        if ( in_array( $post->ID, $custom_bg_page_ids ) ) {
            return $custom_bg_color;
        }
        return $value;
    }
);

About

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