如何从 wordpress 中的小部件(边栏)控制 header 图像背景
How to control the header image background from a widget (sidebar) in wordpress
这是我的目标:
我想通过我用 WordPress 创建的小部件通过小部件部分的后端控制 header 图像(我在侧边栏下添加了一个图像)。
这是我的代码:
<?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>',
) );
}
?>
在模板中我将这样调用侧边栏:
<?php dynamic_sidebar( 'sidebar-1' ); ?>
到目前为止一切顺利,但如果我想做一些不同的事情,比如:
<header style="background-image: url(<?php dynamic_sidebar( 'sidebar-1' ); ?>)"></header>
这种方法的问题是 dynamic_sidebar 函数会调用带有一些额外标记的整个 <div>
,但我的想法是只调用动态侧边栏中的图像。
有什么办法吗?
我建议你使用 Wordpress Customization API
您可以在您的定制器中添加一个设置,然后您可以在任何地方调用它:
// 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',
)));
调用它:
$image_id = get_theme_mod( 'header_image', '' ); // get the image id
$image = wp_get_attachment_image_src( $image_id, 'full' ); // gets the image source
这是我的目标:
我想通过我用 WordPress 创建的小部件通过小部件部分的后端控制 header 图像(我在侧边栏下添加了一个图像)。
这是我的代码:
<?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>',
) );
}
?>
在模板中我将这样调用侧边栏:
<?php dynamic_sidebar( 'sidebar-1' ); ?>
到目前为止一切顺利,但如果我想做一些不同的事情,比如:
<header style="background-image: url(<?php dynamic_sidebar( 'sidebar-1' ); ?>)"></header>
这种方法的问题是 dynamic_sidebar 函数会调用带有一些额外标记的整个 <div>
,但我的想法是只调用动态侧边栏中的图像。
有什么办法吗?
我建议你使用 Wordpress Customization API
您可以在您的定制器中添加一个设置,然后您可以在任何地方调用它:
// 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',
)));
调用它:
$image_id = get_theme_mod( 'header_image', '' ); // get the image id
$image = wp_get_attachment_image_src( $image_id, 'full' ); // gets the image source