2016-08-14 41 views
0

我正在創建一個短代碼,旨在根據情況爲該短代碼動態更改css和js。現在的問題是我沒有得到關於如何在add_shortcode()內使用add_action()的線索。我給大家舉一個例子代碼片段讓你們能更好地理解我:如何在wordpress短代碼內添加內聯css/j

add_shortcode('example', function($atts) { 
    //extracting the shortcode attributes 
    extract(shortcode_atts(array(
     'value1' => null, 
     'value2' => null, 
     'value3' => null 
    ), $atts)); 

    //Now here I wll do my code for the shortcode 
    // But the shortcode needs some js and css to work 
    // so, I'm trying like this 

    //For the CSS 
    add_action('wp_head', function() { 
     echo '<style type="text/css"> 
      .class { 
       background-color: '. $value2 .'; 
      } 
     </style>'; 
    }); 

    //For the JS 
    add_action('wp_footer', function() { 
     echo '<script type="text/javascript"> 
      var a = '. $value3 .' 
     </script>'; 
    }); 

}); 

現在很明顯,它不工作,所以我希望如果你們可以指導我如何將類似的事情在適當的辦法。

如果可以,請幫忙,而不是負面投票的問題。

+0

問題:是否真正有必要在簡碼中使用js和css。我會把CSS放入style.css和javascript部分到一個js文件 – meck373

+0

@ meck373我認爲你沒有正確讀取示例代碼。我不得不這樣做的原因是因爲CSS和JS值將根據短代碼值進行動態更改。正如你在上面看到的,我已經在css&js部分中相應地使用了'$ value2'和'$ value3'。這兩個都來自簡碼。這就是我採取這種方法的原因。如果您有任何其他問題,請告訴我。 – iSaumya

回答

0

應該有更好的方式來做到這一點,但目前只是使它工作,去掉ADD_ACTION()的一部分,只是讓你的代碼的字符串,並將其返回:

add_shortcode('example', function($atts) { 
    //extracting the shortcode attributes 
    extract(shortcode_atts(array(
     'value1' => null, 
     'value2' => null, 
     'value3' => null 
    ), $atts)); 

    //For the CSS 
     $result = '<style type="text/css"> 
      .class { 
       background-color: '. $value2 .'; 
      } 
     </style>'; 

    //For the JS 
     $result .= '<script type="text/javascript"> 
      var a = '. $value3 .' 
     </script>'; 

    return $result; 
}); 
+0

非常感謝您的回覆。但是這似乎並不是一種很好的方式,因爲樣式標籤會在'body'中填充。在做了大量研究之後,我採取了這種方法:http://pastebin.com/eYi6RAbT不確定它是否可行。你可以看看並分享你的想法。 – iSaumya

相關問題