I have a function that I use to populate from checkboxes on a page's edit view (post.php?action=edit). I call this function when I render a metabox on the editor page.
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;
}
For some reason, when I save/update the post, the permalink is changed to having the slug of an attachment! I thought wp_reset_postdata();
would stop the attachment from interfering, but I have no idea what's going on. In the save_post action that I hook into, I only receive numerical IDs of some attachments, I don't call that function again.
EDIT for more info If I echo the post slug, this is the behaviour:
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
Somehow the wp_reset_postdata();
doesn't work