从 wordpress 中的特定页面 ID 或页面 slug 中删除图像 <a> link

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

我需要从我的页面上的图像中删除链接,但仅限于特定页面,或者删除整个网站的所有链接,除了一些页面 ID 或页面别名。

我有删除链接的代码,但我无法添加到例外:

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

你必须使用 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"

---- ( 更新添加了一个遗漏的 ) in if( !is_page( array( 42, 48, 55 ) ) ) { ) ----

比 ID 更通用的是,例如。自定义(元)字段。

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');