1

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

2
  • Where/when are you using this function? – TheDeadMedic May 6 '16 at 8:08
  • 1
    I call it when I render a metabox on the edit page. (I've defined add_action("add_meta_boxes".. which has add_metabox() inside, which says the function to call that renders the metabox.) – juuga May 6 '16 at 8:13
2

I call it when I render a metabox on the edit page. (

Yeah, you shouldn't be using globals in this context - use a foreach loop instead:

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;
}
0

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.