Support

Account

Home Forums General Issues Readout all values of a certain field

Solved

Readout all values of a certain field

  • Hello everyone,

    I have made a field and put several data’s into it. Now, I’d like to read them all out and put them into an array.

    I’m using this inside the functions.php file. But Unfortunately I wasn’t able to do any for each or while.

    As a basic PHP writer, I’m stuck here. Are there any thoughts on how to get all the values of a certain field in an array that I can use in functions.php?

    Thanks in advance.

  • Hi @jordy

    You can achieve this using get_field(...) function. You have to pass the $post_id parameter to this function as explained in the docs.

    Here is the link: http://www.advancedcustomfields.com/resources/get_field

  • Hey James,

    Thanks for your fast reply! Really appreciate it.
    I was able to pass the post_id, but that just gives me one result.

    I would like to fetch the values of all post_id’s from my custom field and put them into an array. Normally you do that with a for each, but loops don’t seem to work within the functions.php.

    Best,
    Jordy

  • Hi @jordy

    Thanks for the clarification.

    Hmm… ACF does not have a function to help you achieve this. You could consider using one of the helper methods in the WPDB class to perform a custom query.

    Check out the solution offered here: http://wordpress.stackexchange.com/questions/9394/getting-all-values-for-a-custom-field-key-cross-post

  • Thank you!

    It seems like things are gonna get a lot harder for me 🙂
    I gonna try this out and if I get it to work, I’ll leave it here how I’ve done it.

    Best,
    Jordy

  • This went faster than I thought. I basically had to copy/paste those codes you linked to.

    Here’s what I did:

    function get_custom_values( $key = 'YOUR_FIELD', $type = 'post', $status = 'publish' ) {
    
    		    global $wpdb;
    
    		    if( empty( $key ) )
    		        return;
    
    		    $custom_arry = $wpdb->get_col( $wpdb->prepare( "
    		        SELECT pm.meta_value FROM {$wpdb->postmeta} pm
    		        LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id
    		        WHERE pm.meta_key = '%s' 
    		        AND p.post_status = '%s' 
    		        AND p.post_type = '%s'
    		    ", $key, $status, $type ) );
    
    		    foreach ($custom_arry as $custom_field) {
    		    	$custom_result.= $custom_field. "SEPARATION_SIGN";
    			}
    
    			return $custom_result;
    		}
    
    		$fina_custom_result = get_custom_values();
Viewing 6 posts - 1 through 6 (of 6 total)

The topic ‘Readout all values of a certain field’ is closed to new replies.