• Resolved bcmann

    (@bcmann)


    I have a custom post type for real estate property listings. I created a metabox for the agent that is listing the property, which comes from another custom post type for agents. All of this is working perfectly. But in order to get the list of agents from the agent post type, I have to perform a WP_Query(). So after the loop, I run wp_reset_postdata() like the documentation shows, but my $post variable doesn’t reset. When I later reference $post->ID, it shows the last ID in the agent query. Any help would be greatly appreciated.

    Here’s my code:

    function listing_agent( $post ){
      $agent = get_post_meta( $post->ID, 'listing_agent', true );
      $lm_query = new WP_Query( 'post_type=lm_agent' );
      ?>
      <div>
        <label for='Listing Agent' class='agent'>
          <select name='listing_agent'>
    	<option value=''>-Select Agent-</option>
    	<?php
    	  if ( $lm_query->have_posts() ) {
    	    while ( $lm_query->have_posts() ) {
    	      $lm_query->the_post();
    	      echo '<option value="' . get_the_ID() . '" ' . ( get_the_ID() == $agent ? 'selected = "selected"' : '' ) . '>' . get_the_title() . '</option>';
    	    }
    	  } else {
    	    echo '<option>No Posts</option>';
    	  }
    	?>
          </select>
        </label>
      </div>
      <?php
        /* Restore original Post Data */
        wp_reset_postdata();
    } // End Agent Box
Viewing 1 replies (of 1 total)
  • Thread Starter bcmann

    (@bcmann)

    If anyone runs into this, I found a solution. I don’t think it’s the best possible solution, but it works. I’m guessing I should have used the hook pre_get_posts, but get_posts() is working.

    Here’s what I did…

    function listing_agent( $post ){
      $agent = get_post_meta( $post->ID, 'listing_agent', true );
    
      $lm_agents = get_posts( 'post_type=lm_agent' );
      ?>
        <div>
          <label for='Listing Agent' class='agent'>
            <select name='listing_agent'>
              <option value=''>-Select Agent-</option>
              <?php
                foreach($lm_agents as $lm_agent) {
                  echo '<option value="' . $lm_agent->ID . '" ' . ( $lm_agent->ID == $agent ? 'selected = "selected"' : '' ) . '>' . $lm_agent->post_title . '</option>';
                }
              ?>
            </select>
          </label>
        </div>
      <?php
    } // End Agent Box

    Hope that helps someone!

Viewing 1 replies (of 1 total)
  • The topic ‘wp_reset_postdata() not working’ is closed to new replies.