Support

Account

Home Forums Add-ons Repeater Field Display content if Repeater Field is empty

Solved

Display content if Repeater Field is empty

  • I’m trying to make a simple document management system with the repeater field. I need to print a button to download a Document attached to the the top repeater field. But if the top Repeater field is empty, it should print “not available” content.

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

    
    $repeater = get_field( 'document' );
    	
    	if( $repeater[0] ) {
    
    		$filesize = filesize( get_attached_file ($repeater[0][ 'file' ][ 'id' ]) );
    		$filesize = size_format($filesize);
    		$filetype = wp_check_filetype( get_attached_file ($repeater[0][ '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. The main problem is that it prints out a dead link if there is nothing in the top repeater. This won’t do. So I now want to add an else condition so that it prints some copy if there is nothing in the first repeater:

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

    I’ve made a lot of attempts to get this working but haven’t been able to make it work. What am I missing here?

  • 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.

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Display content if Repeater Field is empty’ is closed to new replies.