2013-03-13 104 views
-2

Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in ...解析错误逃生PHP

这是我得到

<?php 
     function my_custom_js() { 
     echo " <script>" ; 
     echo " jQuery(document).ready(function(){ 

    jQuery('#secondary-front .first h3').addClass(' 
    <?php $options = get_option('mytheme_theme_options'); 
    if(!empty($options['first_widget_icon'])) echo $options['first_widget_icon']?> '); 

    jQuery('#secondary-front .second h3').addClass('<?php $options =  get_option('mytheme_theme_options'); 
    if (!empty($options['second_widget_icon'])) echo $options['second_widget_icon'];?>'); 

    jQuery('#secondary-front .third h3').addClass('<?php $options =  get_option('mytheme_theme_options'); 
    if (!empty($options['third_widget_icon'])) echo $options['third_widget_icon'];?>'); 
    }); 

    "; 
    echo "</script> "; 
    } 
    add_action('wp_head', 'my_custom_js'); 
?> 

我不能得到这个代码正确逃避错误,我有PHP>的jQuery> PHP

+5

这一切都搞砸了,为什么你在'<?php'标签里有更多'<?php'。重写它的时间 – 2013-03-13 07:18:26

+0

你宁愿开心使用/学习AJAX。 – hjpotter92 2013-03-13 07:19:15

+0

请了解['wp_localize_script'](http://codex.wordpress.org/Function_Reference/wp_localize_script)(和'wp_enqueue_script')。 – hakre 2013-03-13 07:21:02

回答

2

问题在于你的报价(")不会在双方中衡量。这就是说,当我去调查这个问题,我注意到糟糕的事情与你的代码,所以我已经完全重写,它给你:

<?php 

    function my_custom_js() { 
     $options = get_option('mytheme_theme_options'); 

     echo "<script> 
      jQuery(document).ready(function(){ 
       jQuery('#secondary-front .first h3').addClass('" . ($options['first_widget_icon'] ?: NULL) . "'); 
       jQuery('#secondary-front .second h3').addClass('" . ($options['second_widget_icon'] ?: NULL) . "'); 
       jQuery('#secondary-front .third h3').addClass('" . ($options['third_widget_icon'] ?: NULL) . "'); 
      }); 
     </script>"; 
    } 

    add_action('wp_head', 'my_custom_js'); 

?> 

一件事,我所做的就是移动$options = get_option('mytheme_theme_options');到顶端。我也删除了重复的电话。此外,这具有敲门效应,echo可以在1语句中完成,巧妙地使用ternary operator

echo ($something ?: NULL);意味着如果存在$ something,则回显它,否则不回显

使用三元运算符与?:速记需要PHP> = 5.3.0

对于低于这个版本,只是在中间部分填写,即:

// PHP >= 5.3.0 
($options['first_widget_icon'] ?: NULL) 

// PHP < 5.3.0 
($options['first_widget_icon'] ? $options['first_widget_icon'] : NULL) 

当然,代码可能需要根据自己的喜好调整,但它应该是改进的基础。

+0

感谢Danny,所以我不需要回显>($ options = get_option('mytheme_theme_options');)? – brodster 2013-03-13 18:41:08