web-dev-qa-db-ja.com

プラグインの中からwp_queryを実行するための適切な方法

カスタム投稿タイプのクエリを作成し、これらの投稿からデータとメタデータを取得する必要があるプラグインを開発しています。しかし、私がプラグインの中でそのクエリを実行するときはいつでも、どんな管理者の新しい投稿ページ(どんな投稿、カスタム投稿タイプ、またはページ)にプルアップしても、最初のカスタム投稿からのデータがあります。プラグインで問い合わせています。だから、たとえば、私のプラグインの中に私は持っている:

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();
}    

上記のものが私のプラグインに含まれている場合、adminにプルアップされたpost-new.phpページには、記入用に新しい投稿ページを空白にする代わりに、そのカスタム投稿タイプ(mcpt)の最初の投稿が事前に入力されます。

何がこれを引き起こしているのですか?

1
Stephen

これはそれを解決したものです(以下の個々の行動のどれもそれを解決しなかったのでなぜ私はわからないが):

アクションを取り除き、WP Queryからget_postsに変更し、resetを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;
}    
1
Stephen