Support

Account

Home Forums General Issues the_sub_field is returning unwanted information

Solved

the_sub_field is returning unwanted information

  • Spent a few hours trying different solutions but I can’t figure out why the_sub_field is returning all sorts of unwanted info, when I only want the attachment file name.

    Here is my code:

    <?php 
    
    		// check if the repeater field has rows of data
    		if( have_rows('attachments') ):
    
    		 	// loop through the rows of data
    		    while ( have_rows('attachments') ) : the_row();
    
    		        // display a sub field value
    		        $file = get_sub_field('file_attachment');
    		        if( $file ):
    		        ?>
    		        
    		        <a target="_blank" href="<?php echo $file['url']; ?>"><?php the_sub_field('file_attachment'); ?></a>
    		        
    		        <?php endif;
    
    		    endwhile;
    
    		else :
    
    		    // no rows found
    
    		endif;
    
    	?>

    See attachments for reference to the admin settings and front-end display. Any ideas why this is happening and how to just return the file name or url (ex. document.pdf)

  • the_sub_field('file_attachment') gets the same thing that get_sub_field('file_attachment'); returns. The only difference is that the_sub_field() echos the value, in this case a stringified array, and get_sub_field() returns the array. If you want to echo the file name then you need to echo the title array element, or one of the other array elements for other things

    
    <?php 
    
    		// check if the repeater field has rows of data
    		if( have_rows('attachments') ):
    
    		 	// loop through the rows of data
    		    while ( have_rows('attachments') ) : the_row();
    
    		        // display a sub field value
    		        $file = get_sub_field('file_attachment');
    		        if( $file ):
    		        ?>
    		        
    		        <a target="_blank" href="<?php echo $file['url']; ?>"><?php echo $file['title']; ?></a>
    		        
    		        <?php endif;
    
    		    endwhile;
    
    		else :
    
    		    // no rows found
    
    		endif;
    
    	?>
    
  • Thanks, John. Where can I get a list of possible array elements?

  • That’s a good question, I don’t know. This is the information that’s available and what I looked at https://www.advancedcustomfields.com/resources/file/

    What I would do is this to output the array so I can see what’s in it.

    
    $file = get_sub_field('file_attachment');
    echo '<pre>'; print_r($file); echo '</pre>';
    
  • That output array is actually perfect. Thanks a ton!

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

The topic ‘the_sub_field is returning unwanted information’ is closed to new replies.