首页 > 解决方案 > 如果是 amp 将内部链接更改为 amp 版本 (WordPress)

问题描述

我们使用 WordPress,如果链接的页面有 amp 版本,我们希望将 amp 链接到 amp。我们的 amp 结构是这样的:test.de/test/amp

不幸的是,我的functions.php中的这段代码不适用于帖子内容中硬编码的链接。我必须改变什么,所以它适用于每个内部链接:

add_filter( 'post_link', function( $url, $post ) {
    static $recursing = false;
    if ( $recursing ) {
        return $url;
    }
    $recursing = true;
    if ( ! function_exists( 'post_supports_amp' ) || ! post_supports_amp( $post ) ) {
        return $url;
    }
    if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
        $url = amp_get_permalink( $post->ID );
    }
    $recursing = false;
    return $url;
}, 10, 2 );

目前它也适用于规范链接,这对 seo 来说真的很糟糕。如何防止这种情况?

标签: phpwordpressamp-htmlgoogle-amp

解决方案


将这些函数添加到主题的“functions.php”中。

/* post link filter */
add_filter( 'post_link', 'change_amp_url', 10, 2 );

function change_amp_url( $url, $postobj ) {
    static $recursing = false;
    if ( $recursing ) {
        return $url;
    }

    $recursing = true;
    if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
        if ( function_exists( 'post_supports_amp' ) && post_supports_amp( $postobj ) ) {
            $url = amp_get_permalink( $postobj->ID );           
        }
    }
    $recursing = false;
    return $url;
}

/* content link filter */
add_filter( 'the_content', 'change_amp_url_content' );

function change_amp_url_content($content)
{
    $dom = new DOMDocument();
    $dom->loadHTML($content);

    $tags = $dom->getElementsByTagName('a');
    foreach ($tags as $tag) {
        $link = $tag->getAttribute('href'); // original url
        $extralink = '';
        if(stristr($link,'#')) {
            $pagelinktemp = explode("#",$link);
            $pagelink = $pagelinktemp[0];
            $extralink = '#'.$pagelinktemp[1];
        } else {
            $pagelink = $link;
        }
        if($pagelink!="") {     
            $postid = url_to_postid($pagelink);
            $postobj = get_post($postid); // getting appropriate post object            
            if($postobj) {          
                $newlink = change_amp_url( $pagelink, $postobj ); //new url
            }
            else {
                $newlink = $link;
            }
        }
        else {
            $newlink = $link;
        }
        if($link != $newlink) // change if only links are different
        {
            $content = str_replace($link, $newlink.$extralink, $content);
        }
    }
    return $content;
}

/* override canonical link */
add_filter( 'wpseo_canonical', 'amp_override_canonical' );

function amp_override_canonical($url) {
    if ( substr($url,-4)=="/amp" ) {    
        $url = substr($url,0,-4);
    }
    return $url;
}

如果存在,第一个函数将提供 AMP URL。

第二个将遍历内容中的每个 URL,如果有效,则更改为 AMP URL。

最后一个将重写通过 Yoast SEO 插件显示的规范 URL。


推荐阅读