[英]How to add custom javascript code in the Wordpress file “single.php”
[英]How can I add Wordpress php code into JavaScript
我有以下javascript代碼:
$(window).scroll(function() {
if($(this).scrollTop() > 50) /*height in pixels when the navbar becomes non opaque*/
{
$('.navbar-default').addClass('sticky');
$('.navbar-brand img').attr('src','assets/images/logo.png'); //change src
} else {
$('.navbar-default').removeClass('sticky');
$('.navbar-brand img').attr('src','assets/images/logo__footer.png')
}
});
是否可以插入一個wp自定義PHP代碼
<?php the_custom_logo(); ?>
而不是這個靜態屬性
.attr('src','assets/images/logo.png');
提前謝謝了。
您需要在模板中設置變量:
<script>
var logoImage = <?php the_custom_logo(); ?>;
var logoImageFooter = <?php the_custom_logo()?> //here footer logo
</script>
而且,在你的js文件中使用它
$(window).scroll(function() {
if($(this).scrollTop() > 50) /*height in pixels when the navbar becomes non opaque*/
{
$('.navbar-default').addClass('sticky');
$('.navbar-brand img').attr('src',logoImage); //change src
} else {
$('.navbar-default').removeClass('sticky');
$('.navbar-brand img').attr('src',logoImageFooter)
}
});
你的Js代碼:
$(window).scroll(function() {
if($(this).scrollTop() > 50) /*height in pixels when the navbar becomes non opaque*/
{
$('.navbar-default').addClass('sticky');
$('.navbar-brand img').attr('src','custom_logo.png'); //change src
} else {
$('.navbar-default').removeClass('sticky');
$('.navbar-brand img').attr('src','logo_footer.png')
}
});
HTML代碼:
<?php $customLogo= 'custom_logo'; ?>
<?php $footerLogo= 'footer_logo'; ?>
<html>
<body>
<script type="text/javascript">
// notice the quotes around the ?php tag
var customLogo="<?php echo $customLogo; ?>";
var footerLogo="<?php echo $footLogo; ?>";
alert(customLogo);
alert(footerLogo);
</script>
</body>
</html>
如果你需要jquery與PHP代碼輸入然后wp_localize_script()
函數。 更多信息
var logoImage = <?php the_custom_logo(); ?>;
var logoImageFooter = <?php the_custom_logo()?> //here footer logo
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$translation_array = array(
'logo_image' => the_custom_logo(),
'logo_image_footer' => the_custom_logo()'
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
您可以按如下方式訪問JavaScript中的變量:
<script>
alert( object_name.logo_image);
alert( object_name.logo_image_footer);
</script>
$('.navbar-brand img').attr('src',object_name.logo_image); //change src
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.