我有一个用于从页面编辑视图(post.php?action=edit)上的复选框填充的函数。在编辑器页面上呈现元盒时,我调用此函数。
function get_available_attachments() {
global $post;
$attachments = [];
$attach_query = new WP_Query([
\'post_type\' => \'attachment\',
\'post_status\' => \'inherit\', // default is \'publish\'
\'post_mime_type\' => \'application/pdf\',
\'orderby\' => \'name\',
// \'orderby\' => \'date\',
\'order\' => \'DESC\',
]);
while($attach_query->have_posts()) {
$attach_query->the_post();
$attachments[] = (object)[
\'mime_type\' => $post->post_mime_type,
\'title\' => $post->post_title,
\'ID\' => $post->ID
];
}
wp_reset_postdata();
return $attachments;
}
出于某种原因,当我保存/更新帖子时,
the permalink is changed to having the slug of an attachment! 我想
wp_reset_postdata();
会阻止依恋的干扰,但我不知道发生了什么。在我挂接到的save\\u post操作中,我只收到一些附件的数字ID,不再调用该函数。
EDIT for more info如果我回应后段塞,这就是行为:
function get_available_attachments() {
global $post;
echo $post->post_name .\'<br>\'; // correctly page slug
$attachments = [];
$attach_query = new WP_Query([
// ...
echo $post->post_name .\'<br>\'; // correctly an attachment slug
wp_reset_postdata();
echo $post->post_name .\'<br>\'; // INCORRECT still attachment slug
不知怎么的
wp_reset_postdata();
不起作用
最合适的回答,由SO网友:TheDeadMedic 整理而成
当我在编辑页面上呈现元盒时,我调用它。(
是的,在此上下文中不应该使用全局变量-使用foreach
改为循环:
function get_available_attachments( $post /* This is the post object being edited */ ) {
$attachments = [];
$attach_query = new WP_Query([
\'post_type\' => \'attachment\',
\'post_status\' => \'inherit\', // default is \'publish\'
\'post_mime_type\' => \'application/pdf\',
\'orderby\' => \'name\',
// \'orderby\' => \'date\',
\'order\' => \'DESC\',
]);
foreach ( $attach_query->posts as $att ) {
$attachments[] = ( object ) [
\'mime_type\' => $att->post_mime_type,
\'title\' => $att->post_title,
\'ID\' => $att->ID
];
}
return $attachments;
}