2014-04-26 31 views
-1

我有一個插件讓我獲取自定義字段。我正在工作的主題是一本雜誌,一些作家有Twitter帳戶,有些則沒有。PHP如果Else總是顯示ELSE並打印變量

我想在每種情況下顯示不同的框。

這裏是我的代碼:

<?php 
    $twit = the_field('twitter'); 
    ?> 

    <?php 
     if (!empty($twit)) { 
    ?> 

        <p> <?php the_field('autor'); ?> | <a href="https://twitter.com/<?php echo rawurlencode (the_field('twitter')); ?>" class="twitter-follow-button" data-show-count="false" data-lang="es" data-dnt="true">Seguir a @<?php echo rawurlencode (the_field('twitter')); ?></a> 
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+'://platform.twitter.com/widgets.js';fjs.parentNode.insertBefore(js,fjs);}}(document, 'script', 'twitter-wjs');</script> | <?php the_field('fotos'); ?> |</p> 

    <?php } else { ?> 

      <p>Nothing to see here</p> 

    <?php } ?> 

的「沒什麼可看這裏」的段落是隻是爲了測試,這個想法是擺脫作者日期和照片的信息,並創建一個不同的句子。

這個代碼的問題是,在任何情況下,我都得到Nothing來看到這裏的消息,如果twit字段存在,它會被打印出來,並且從試驗和錯誤中,它看起來從我打印時創建變量$twit

+1

使用var_dump來檢查變量,這將有助於調試。 –

+0

你試過了嗎if($ twit!=「」)'? – Howli

+0

@ПавелИванов當twitter字段存在時,它會打印在一邊,但如果使用var_dump,它會在其旁邊顯示NULL。例如,如果twitter是Foobar,它將顯示FoobarNULL。當twitter不存在時,它只顯示NULL。 – luquiyahni

回答

1

您正在使用錯誤的功能。

the_field將回顯該字段的內容,而不返回任何內容。如果您希望它返回一個值,則需要使用get_field

嘗試:

$twit = get_field('twitter'); 

的WordPress有很多具有相當類似名稱的函數,它的價值一點時間閱讀文檔。通常,返回值的函數始終以get_開頭。

+0

你是對的!這固定了它。謝謝。我希望在此之後,我永遠不會忘記這條規則。再次感謝。 – luquiyahni

+0

很高興幫助! – andrewsi