正在删除图片<a> link from specific page IDs or page slug in wordpress

时间:2016-04-29 12:00:23

标签: php html wordpress tags wordpress-hook

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

2 个答案:

答案 0 :(得分:0)

您必须使用Wordpress条件函数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;
    }
}

您可以使用页面ID或页面标题,例如"contact-us" ...

----(已在 ) 中添加了 if( !is_page( array( 42, 48, 55 ) ) ) { 的更新内容---- < / p>

答案 1 :(得分:0)

比ID mentioned in LoicTheAztec's answer更通用的是例如。自定义(元)字段。

function bw_content($content)
{
    if (get_post_meta(get_the_ID(), 'bw_remove_image_links', true) == 1) {
        $content = preg_replace(array(
            '{<a(.*?)(wp-att|wp-content\/uploads)[^>]*><img}',
            '{ wp-image-[0-9]*" /></a>}'
        ), array(
            '<img',
            '" />'
        ), $content);
    }
    return $content;
}
add_filter('the_content', 'bw_content');