I wanted to remove the images from a WordPress post to give me more control of how I could layout the design for the front page of a website. After doing some messing around and failing, I finally found a great post which had an amazing little piece of code that solved my problem.

$content = get_the_content();
$postOutput = preg_replace('/<img[^>]+./','', $post->post_content);
echo $postOutput;

But some time i have link above images like:

<a href="#"><img src="PATH_IMAGES"></a>

So, How can remove it?

  • 2
    Just like you did, but with different regex. This looks like a pure PHP question to me and as such is off topic here.
    – s_ha_dum
    Commented May 12, 2015 at 19:45

1 Answer 1

delete_attachment( $attachment_id, true );
wp_delete_post( $attachment_id, true );

Are your best friends. You will need something like this:

$args = array(
    'post_type'    => 'attachment',
    'numberposts'  => null,
    'post_status'  => null,
    'post_parent'  => $post->ID,
    'post__not_in' => array(
        get_post_thumbnail_id( $post->ID )
$attachments = get_posts( $args );
if ( $attachments ) {
    foreach ( $attachments as $attachment ) {
        delete_attachment( $attachment_id, true );
        wp_delete_post( $attachment_id, true );

The "true" statement defines that the attachments and their IDs are completely removed from the backend and filesystem. If you want to store them into the trash, then set it to false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.