• H2GD Part 45: How to remain detached?

    H2GD Part 45: How to remain detached?

    How to prevent WordPress from attaching an unattached image to a post when you use Insert into post.

    Here’s a snippet of code that I wrote in response to a simple question from Ben Huson, posed on Twitter yesterday.

     * Implement 'wp_ajax_send-attachment-to-editor' to not attach an unattached media item
     * In WordPress TRAC 22085 there was a change
     * that caused unattached media files (images) to be attached to posts if they are inserted into the post.
     * If you don't like this strategy you can disable it using this simple, rather hacky, action hook.

    function dont_attach( $blah ) {
            $_POST['post_id'] = 0;
     * Hook into the AJAX request before WordPress, using priority 0

    add_action( 'wp_ajax_send-attachment-to-editor', 'dont_attach', 0 );


    Additional notes

    This solution relies on the following code being in [api wp_ajax_send_attachment_to_editor()].

    if ( 0 == $post->post_parent && $insert_into_post_id = intval( $_POST['post_id'] ) ) {
      wp_update_post( array( 'ID' => $id, 'post_parent' => $insert_into_post_id ) );

    It also relies on there being no other code that requires the post_id value. If this were not the case then we’d have to:

    • reset it in a later hook, which doesn’t look particularly possible.
    • or implement a different solution to cause [api current_user_can()] to fail.
    • or apply a pretend setting of $post->post_parent at the end of [api get_post()].

    BTW: It’s not a problem with WordPress 4.2.2.

    Alternative approaches

    If you don’t want to use this code…

    • Don’t use Insert into post; use a shortcode instead. In this post I’ve used [bw_fields featured] to display the featured image. The shortcode will display whatever image is currently marked as the featured image.
      Note: Setting a Featured image does not cause an unattached image to be attached to a post.
    • Develop your own solution for the ticket that Ben raised. core.trac.wordpress.org/ticket/32999



    Last updated:

    July 15, 2015

Today’s word is this:







Tide times from tidetimes.org.uk

Tide Times & Heights for Langstone Harbour on
24th May 2024
00:39 High Tide ( 4.72m )
05:52 Low Tide ( 1.15m )
13:04 High Tide ( 4.63m )
18:10 Low Tide ( 1.25m )

Tide times from tidetimes.org.uk

Tide Times & Heights for Northney on
24th May 2024
00:44 High Tide ( 4.4m )
05:50 Low Tide ( 0.77m )
13:11 High Tide ( 4.31m )
18:05 Low Tide ( 0.97m )