duanrang2627 2016-09-11 20:30
浏览 50
已采纳

如何组合字符串用作php var?

While using Advanced Custom Fields for Wordpress I got to call some vars using get_field('my-custom-field');

I got this code which I would like to store in a function:

<img src="<?php the_sub_field('image-1'); ?>"> 
<?php $target_post = get_sub_field('target-1'); ?> 
<?php echo get_the_title($target_post); ?>

All I need to replace inside my function is the -1 to -2, -3, etc. How can I do this?

I have tried this, which does not work:

function imageBlock($fieldID = '1') {
   <img src="<?php the_sub_field('image-$fieldID'); ?>"> 
   <?php $target_post = get_sub_field('target-$fieldID'); ?> 
   <?php echo get_the_title($target_post); ?>
}

How can I pass the fieldID to the get_field('my-custom-field-1'); function?

  • 写回答

1条回答 默认 最新

  • dongshai8330 2016-09-11 20:32
    关注

    You're trying to pass a variable into a single quoted string which will take the literal $ as part of the string, not the start of a variable. There are two ways to correct this.

    Either with;

    get_sub_field("target-$fieldID"); // double quotes
    

    or

    get_sub_field('target-' . $fieldID); // concat
    

    So your function would be;

    function imageBlock($fieldID = '1') {
        ?>
        <img src="<?php the_sub_field("image-$fieldID"); ?>"> 
        <?php $target_post = get_sub_field("target-$fieldID"); ?> 
        <?php
        echo get_the_title($target_post);
    }
    

    Having said that, I would split the logic out so that you were just returning the string of HTML like the other functions you're calling;

    function imageBlock($fieldID = '1') {
        $sub_field = the_sub_field("image-$fieldID");
        $target_post = get_sub_field("target-$fieldID");
        $the_title = get_the_title($target_post);
    
        return "<img src=\"$sub_field\"> $the_title";
    }
    

    and you can echo the result, ie;

    echo imageBlock(2);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料