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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?