0
votes

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?

1
you have just created a widget area, not a widget, which widget are you using for the image? if you want to retrieve the image url and style it, it will have to be done within the widget code (not widget area)decoder88

1 Answers

1
votes

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