首页 > 解决方案 > 为 AMP 页面交换 HTML

问题描述

有没有办法更改 AMP 页面中的 HTML?例子:

使每个<span class="example1">...</span>to<a href="example1">...</a> 甚至更好,将 Wordpress 中的特定短代码更改为<a href="example1">...</a>?

标签: phphookamp-htmlgoogle-amp

解决方案


我找到了切换简码的解决方案:

// AMP change thrive-shortcode to landingpage link
function add_shortcode_amp($content) {
    if (function_exists( 'is_amp_endpoint' ) && is_amp_endpoint()) {
        /// Define shortcode-name
        $mb_shortc = 'thrive_2step';
        /// Define Mappings (thrive_2step id => Target URL for links in AMP)
        $ampMappings = array(
            "17503" => 'https://www.test.de/schreibtisch-workout-2',
            "17505" => 'https://www.test.de/merkmale-arbeitsplatz-kostenlos',
            "17506" => 'https://www.test.de/hoehenverstellbarer-schreibtisch-rentenverischerung-antrag');

        /// Init Regex arrays
        $mb_rexp =  array();
        $subst = array();
        foreach ($ampMappings as $key => $value) {
            $mb_rexp[] = '/\[('.$mb_shortc.').*?.id=[\'"]'.$key.'[\'"].*?\](.*?)\[\/\1\]?/';
            $subst[] = '<a href="'.$value.'">${2}</a>';     
        }
        /// Process Content
        return preg_replace($mb_rexp, $subst, $content);
    }
    return $content;
}
add_filter( 'the_content', 'add_shortcode_amp', 6); 

function mbtest_hello_world() {
    return '<a>Hello World</a>';
}
add_shortcode('AMPTEST', 'mbtest_hello_world'); 

function shortcode_switch4amp( $atts) {
    extract( shortcode_atts( array(
      'regular' => 'regular',
      'amp' => 'amp'
      ), $atts ) );
    if (function_exists( 'is_amp_endpoint' ) && is_amp_endpoint()) {
        return do_shortcode(str_replace(array("{","}"), array("[","]"),$amp));
    } else {
        return do_shortcode(str_replace(array("{","}"), array("[","]"), $regular));
    }               
}
add_shortcode('switch4amp', 'shortcode_switch4amp');

推荐阅读