TomaszKub TomaszKub - 5 months ago 7
PHP Question

Removing image <a> link from specific page IDs or page slug in wordpress

I need to remove links from images on my page, but only on specfic pages, or remove all the links all over the website, except a few page id's or page slugs.

I have the code for removing links, but I can't add to the exceptions:

add_filter( 'the_content', 'attachment_image_link_remove_filter' );

function attachment_image_link_remove_filter( $content ) {
$content =
preg_replace(
array('{<a(.*?)(wp-att|wp-content\/uploads)[^>]*><img}',
'{ wp-image-[0-9]*" /></a>}'),
array('<img','" />'),
$content
);
return $content;
}

Answer

You have to use the Wordpress conditional function is_page():

add_filter( 'the_content', 'attachment_image_link_remove_filter' );
function attachment_image_link_remove_filter( $content ) {
    // Set your exception pages in here
    if( !is_page( array( 42, 48, 55 ) ) ) {
        $content = preg_replace( 
            array('{<a(.*?)(wp-att|wp-content\/uploads)[^>]*><img}',
                '{ wp-image-[0-9]*" /></a>}'),
            array('<img','" />'),
            $content
        );
        return $content;
    }
}

You can use page IDs or page slugs like "contact-us"

---- ( updated adding a missing ) in if( !is_page( array( 42, 48, 55 ) ) ) { ) ----

Comments