doupao6698 2018-11-23 02:45
浏览 82
已采纳

如果第一个ACF Repeater字段为空,则打印内容

I’m trying to make a simple document management system with ACF's repeater field. I need to print a button to download a file attached to the the top repeater field (with the size and filetype of the download). But if the top repeater field is empty, it should print “file not available” content.

I’m pretty new to PHP but this mostly works so far:

$repeater = get_field( 'document' )[0];

    if( $repeater ) {

        $fileurl = $repeater[ 'document' ][ 'url' ];
        $filesize = filesize( get_attached_file ($repeater[ 'file' ][ 'id' ]) );
        $filesize = size_format($filesize);
        $filetype = wp_check_filetype( get_attached_file ($repeater[ 'file' ][ 'id' ]));

        $download = '<div><a href="' . $repeater[ 'file' ][ 'url' ] . '">Download</a><div>' . $filesize . ' <span>' . $filetype[ 'ext' ] .'</span></div></div>' ;

                echo $download;
        }

This prints a button to the attached file in the top repeater, when there is an attached file in the top repeater. Only it prints out a dead link if there is nothing in the top repeater. This won’t do. I need to add an else condition or something so that it prints "file not available" content if there is nothing in the first repeater.

    if(empty( $repeater )) {

        $unavailable = '<div>Unavailable<div>This document isn\'t ready yet. Please check back later.</div></div>' ;

                echo $unavailable;
        }

I've tried a lot of different ways to do this, such as above, and I don't know what I'm doing wrong. Can you help?

  • 写回答

3条回答 默认 最新

  • duanshaiduhao2471 2018-11-25 23:30
    关注

    I finally got it! I think I wasn't declaring my variables clearly enough.

    $row = get_field( 'document' );
    $first_row = $row[0];
    $first_row_file = $first_row[ 'file' ];
    
    if( $first_row_file ) :
    
                $download = '<div>Available!<div>This document is ready for download.</div></div>' ;
    
                        echo $download;
    
    else :
    
                $unavailable = '<div>Unavailable!<div>This document isn\'t ready yet. Please check back later.</div></div>' ;
    
                        echo $unavailable;
    
    endif;
    

    Now I can add more sophisticated content (like a download button) to display when there is a file to download, and a helpful message when there isn't.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?
  • ¥20 用户端如何上传图片到服务器和数据库里
  • ¥15 现在研究生在烦开题,看了一些文献,但不知道自己要做什么,求指导。
  • ¥30 vivado封装时总是显示缺少一个dcp文件
  • ¥100 pxe uefi启动 tinycore
  • ¥15 我pycharm运行jupyter时出现Jupyter server process exited with code 1,然后打开cmd显示如下
  • ¥15 可否使用carsim-simulink进行四轮独立转向汽车的联合仿真,实现四轮独立转向汽车原地旋转、斜向形式、横移等动作,如果可以的话在carsim中如何进行相应设置
  • ¥15 Caché 2016 在Java环境通过jdbc 执行sql报Parameter list mismatch错误,但是同样的sql使用连接工具可以查询出数据
  • ¥15 疾病的获得与年龄是否有关