1

I am developing a plugin that needs to make a query of a custom post type and retrieve data and meta data from these posts. But anytime I run that query inside my plugin, no matter what admin new post page I pull up (in any post, custom post type, or page) there is data that is pre-filled in, and it is from the first custom post type I am querying in my plugin. So, for example, inside my plugin I have:

add_action('wp','myfunction');
function myfunction(){
$mcpt_query = array();

$the_query = new WP_Query('post_type=mcpt');

if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post(); 
   $mcpt_query[] = array(
        'id'       => get_post_meta(get_the_ID(), 'idkey', true ),
        'field1'   => get_post_meta(get_the_ID(), 'field1key', true ),
        'title'    => get_the_title($post->ID)
    );
endwhile;
endif;
return $mcpt_query;
wp_reset_postdata();
}    

And if the above is in my plugin, any post-new.php page pulled up in admin will be prefilled with the first post from that custom post type (mcpt), instead of giving me a blank new post page to fill out.

Any ideas what is causing this?

  • What happens if you don't attach it to an action? Run the thing on an admin page directly so you don't do it on every page load. – Andrew Bartel May 20 '14 at 4:32
  • even if I comment out the action, I still get the same data error. – Stephen May 20 '14 at 4:40
  • @Stephen wp_reset_postdata() is never called because it is after the return, put it before the return and it should work. Moreover, if you don't want the function affect admin in any way, just put if ( is_admin() ) return; in first function line. – gmazzap May 20 '14 at 4:45
  • Actually, this plugin is all for admin, nothing for frontend, so I want it to run in admin. And I have moved wp_reset_postdata (and tried wp_reset_query) in the spot before the return to no avail. Still same data problem in any new post – Stephen May 20 '14 at 4:48
  • BUT, it seems a combo of moving reset_postdata, and moving to a foreach loop and using get_posts instead of wp query seems to have done the trick! – Stephen May 20 '14 at 4:51
1

Here is what solved it (although I am not sure WHY since any of the individual actions below did NOT solve it):

I got rid of the action, changed from WP Query to get_posts, and moved reset above return.

function myfunction(){
$mcpt_query = array();

$the_query = get_posts('post_type=mcpt');

foreach ( $the_query as $post ) : setup_postdata( $post );
$mcpt_query[] = array(
    'id'       => get_post_meta(get_the_ID(), 'idkey', true ),
    'field1'   => get_post_meta(get_the_ID(), 'field1key', true ),
    'title'    => get_the_title($post->ID)
);
endforeach;
wp_reset_postdata();
return $mcpt_query;
}    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.