Support

Account

Home Forums Bug Reports get_field() resets $post?

Solving

get_field() resets $post?

  • Today i noticed strange behavior which seems caused by get_field function.

    I have following code in page template file:

    	<?php
    	$args = array(
    		'numberposts' 	=> 8,
    		'post_type' 	=> 'items',
    		'order'		=> 'ASC'
    	);
    
    	$items = get_posts( $args ); ?>
    
    ....
    
    <?php $i = 0; foreach( $items as $post ): setup_postdata($post); ?>
    .....
    <?php 
    	_log($post);
    	$mods = get_field('mod');
    	_log($post);
    

    So, before get_field() call logged $post value is correct, however after call the $post seems gets overwritten with global $post value of the page. Also it seems it happens only on first iteration of foreach.

    I guess its not supposed to work in this way?

  • What is _log()? I can’t find any reference to this function in WP or PHP.

  • Just an internal function i use for debugging. It saves variable state. I kept it in snippet to show that value of $post is checked right before and after of call of get_filed() function.

  • I guess the important question is, do you get the right output. If you loop through several posts and output post data and custom fields are the values output from the posts you’re looping over or from the global $post?

    If it’s outputting the wrong data then you’ve probably got something else that may be interfering.

  • That is what i tried to show in first post:

    1. In custom page template file (so global $post variable is set already) i create secondary loop using get_pages() (btw using WP_Query doesnt change anything).

    2. I iterate through get_pages() results and use setup_postdata() to set global variables up.

    3. Right before get_field() call i check $post value and its correct. Right after the call i check $post again and see that now it holds value of global $post.

    4. Whole this thing seems happens only on first iteration. The rest of the loop data seems correct.

    Finally if im commenting out get_field() call then $post values are correct for entire secondary loop. So i am pretty sure that whole this thing has something to do with ACF 🙂

  • I just did a quick test. I don’t have the same post types you have I just used posts. This is on a site that only has ACF active. The same post is output before and after using get_field(), so I’m not seeing anything in ACF.

    Unless it has to do with the specific field you’re getting. What type of field is 'mod'?

    
    $args = array(
    	'post_type' 	=> 'post',
    	'order'		=> 'ASC'
    );
    
    $items = get_posts( $args );
    foreach( $items as $post ) {
    	setup_postdata($post);
    	echo 'BEFORE<pre>'; print_r($post); echo '</pre>';
    	$field = get_field('test_field');
    	echo 'AFTER<pre>'; print_r($post); echo '</pre>';
    }
    
Viewing 6 posts - 1 through 6 (of 6 total)

The topic ‘get_field() resets $post?’ is closed to new replies.