簡體   English   中英

如何從Wordpress中的小部件(邊欄)控制標題圖像背景

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

這是我的目標:

我想通過使用WordPress創建的小部件通過小部件部分的后端控制標題圖像(我在側邊欄下方添加了圖像)。

這是我的代碼:

<?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>',

    ) );
}

?>

在模板中,我將以這種方式調用sidbar:

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

到目前為止很好,但是如果我想做一些不同的事情,例如:

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

這種方法的問題在於,dynamic_sidebar函數將使用一些額外的標記來調用整個<div> ,但是我的想法是僅從動態側欄中調用圖像。

有什么辦法嗎?

我建議您使用Wordpress 自定義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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM