phphookamp-htmlgoogle-amp

Exchange HTML in for AMP Pages


Is there a way to change HTML in AMP Pages? Example:

Make every <span class="example1">...</span> to <a href="example1">...</a> Or even better, change specific Shortcodes in Wordpress to <a href="example1">...</a>?


Solution

  • I found a solution to switch shortcodes:

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