简体   繁体   中英

How to control the header image background from a widget (sidebar) in wordpress

Here's my goal:

I want to control the header image through the backend in the widget section (I added an image under my sidebar) through a widget that I create with WordPress.

Here's my code:

<?php

add_action( 'widgets_init', 'theme_slug_widgets_init' );
function theme_slug_widgets_init() {
    register_sidebar( array(
        'name' => __( 'Main Sidebar', 'theme-slug' ),
        'id' => 'sidebar-1',
        'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'theme-slug' ),
        'before_widget' => '<div>',
        'after_widget'  => '</div>',

    ) );
}

?>

and in the template I will call the sidbar in this way:

<?php dynamic_sidebar( 'sidebar-1' ); ?>

So far so good but what if I want to do something different, like:

<header style="background-image: url(<?php dynamic_sidebar( 'sidebar-1' ); ?>)"></header>

The problem of this approach is that the dynamic_sidebar function will call the entire <div> with some extra markup, but my idea is to call only the image from the dynamic sidebar.

Is there any way to do that?

I suggest you make use of the Wordpress Customization API

You can add a setting in your Customizer, that you can then call where ever:

    // Header Image.
    $wp_customize->add_setting('header_image', array( // header_image is your preferred name
        'default' => '',
        'transport' => 'refresh',
    ));
    $wp_customize->add_control( new WP_Customize_Media_Control( $wp_customize, 'header_image', array(
        'label' => __( 'header_image', 'your_theme' ),
        'section' => 'your_section',     // read more on what sections exist and how to implement them
        'mime_type' => 'image',
    )));

to call it:

$image_id = get_theme_mod( 'header_image', '' ); // get the image id
$image = wp_get_attachment_image_src( $image_id, 'full' );  // gets the image source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM