Support

Account

Home Forums General Issues using the_field() in functions.php?

Solving

using the_field() in functions.php?

  • I’m trying to get this to work in functions.php but it doesn’t want to work at all. I just need the function to get all the field ‘order_number’ values in an array and then use the max function on the array.

    function load_highest_order_number()
    {
    	$category7 = query_posts('meta_key=order_number&cat=7');
    	while ( have_posts() ) : the_post(); 
    		echo the_field('order_number');
    	endwhile;
    	wp_reset_query();
    	return max($array);
    }
  • Hi @chanshaw

    To use a template function e.g. the_field(…) in function.php, you have to add a second parameter; the $post_id which tells ACF from where to grab the values from.

    Try this:

    function load_highest_order_number()
    {
    	$category7 = query_posts('meta_key=order_number&cat=7');
    	while ( have_posts() ) : the_post(); 
    		echo get_field('order_number', get_the_ID());
    	endwhile;
    	wp_reset_query();
    	return max($array);
    }

    Check out the following links for more information:
    http://www.advancedcustomfields.com/resources/get_field/
    http://www.advancedcustomfields.com/resources/the_field/

    Hope this helps 🙂

  • Hi James, thank you for the reply, I’ve been trying to figure this out for some time now. It seems when I use this code I get an unlimited loop. get_field does not seem to work for me in functions.php

  • here is the rest of the code thats in my functions.php, maybe thats the problem

    function load_highest_order_number()
    {
    	$category7 = query_posts('meta_key=order_number&cat=7');
    	while ( have_posts() ) : the_post(); 
    		echo get_field('order_number', get_the_ID());
    	endwhile;
    	wp_reset_query();
    	return max($array);
    }
    
    function my_acf_load_field( $field )
    {
    	$field['default_value'] = "Number Calculated: " . load_highest_order_number();	
    	return $field;
    }
    
    add_filter('acf/load_field/name=order_number', 'my_acf_load_field');
  • @acf-support

    I’m not sure if I had to tag you in order for you to see this?

  • Hi @chanshaw

    Hmm… Please change the method query_posts() and use get_posts() instead and change your code to the following:

    function load_highest_order_number() {
    	$args = array(
    		'meta_key' 	=> 'order_number',
    		'cat'		=> 7);
    
    	$posts = get_posts($args);
    	foreach ($posts as $post):
    		echo get_field('order_number', $post->ID);
    	endforeach;
    	... // 
    }

    Have a look at the documentation of get_posts() and query_posts() for more information on this. Here are the links:
    https://codex.wordpress.org/Function_Reference/query_posts
    https://codex.wordpress.org/Template_Tags/get_posts

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

The topic ‘using the_field() in functions.php?’ is closed to new replies.