简体   繁体   English

如何从Wordpress中的小部件(边栏)控制标题图像背景

[英]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. 我想通过使用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: 在模板中,我将以这种方式调用sidbar:

<?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. 这种方法的问题在于,dynamic_sidebar函数将使用一些额外的标记来调用整个<div> ,但是我的想法是仅从动态侧栏中调用图像。

Is there any way to do that? 有什么办法吗?

I suggest you make use of the Wordpress Customization API 我建议您使用Wordpress 自定义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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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