簡體   English   中英

無法在Wordpress自定義小部件區域中運行代碼

[英]Unable run the code in wordpress custom widget area

我已經在WordPress 4.8版本中創建了一個小部件區域,在該小部件區域中,我正在使用文本小部件。

碼:

<div id='div-gpt-ad-xxxxxxxxxxxxx-x'>
<script>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-xxxxxxxxxxxxx-x'); });
</script>
</div>

小部件創建代碼:

global $blog_id;
if( $blog_id == '2' ) {

    function wpb_widgets_init() {

    register_sidebar( array(
        'name'          => 'Header Widget Area for RBI',
        'id'            => 'custom-header-widget',
        'before_widget' => '<div class="chw-widget">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="chw-title">',
        'after_title'   => '</h2>',
    ) );

}
add_action( 'widgets_init', 'wpb_widgets_init' );

}
<?php
global $blog_id;
if( $blog_id == '2' ) {

if ( is_active_sidebar( 'custom-header-widget' ) ) : ?>
    <div id="header-widget-area" class="chw-widget-area widget-area" role="complementary">
    <?php dynamic_sidebar( 'custom-header-widget' ); ?>
    </div>

<?php endif; } ?>

上面的腳本,如果我們直接將其放置在header.php或footer.php文件中,則可以正常工作,但在文本小部件中則無法解決任何問題

通常,您不能將PHP直接放在小部件中,Wordpress不允許。 有一些插件可以讓您做到這一點,但是我不能擔保任何一個插件,因此我會讓您自己找到它。

您可以使用簡碼來完成此操作。

首先,您可以在widgets.php中的以下代碼行中啟用短代碼:

add_filter( 'widget_text', 'do_shortcode' );

接下來,您創建一個簡碼:

function mygooglead_shortcode() {
    ob_start();
    ?>
<div id='div-gpt-ad-xxxxxxxxxxxxx-x'>
<script>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-xxxxxxxxxxxxx-x'); });
</script>
</div>
    <?php
    return ob_get_clean();  
}
add_shortcode( 'mygooglead', 'mygooglead_shortcode' );

最后。 您可以通過以下方式在小部件中使用簡碼:

[mygooglead]

暫無
暫無

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

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