Let’s override the blacklist sanitizer to allow forms in AMP.
First Create a new plugin say AMP Custom Plugin (You can check this tutorial if you don’t know how to do it: Custom Plugin for AMP )
Create a new file for the class in the AMP Custom Plugin folder you have just created say “class-amp-blacklist“
In“class-amp-blacklist“ include the blacklist sanitizer class and write a new class to extend AMP_Blacklist_Sanitizer.
Here is the code to achieve this task:
When you go down in the code you will see a function called get_blacklisted_tags, this is the function which is stripping the tags like form. As you can see I have commented the elements which will make the form to work in AMP.
Call this file in the main file of AMP Custom Plugin
add_action('init', 'amp_new_class_sanitizer'); function amp_new_class_sanitizer() { require_once plugin_dir_path(__FILE__) .'/class-amp-blacklist.php'; }
Unset the AMP_Blacklist_Sanitizer and add Set our new class for the sanitization.
add_filter('amp_content_sanitizers','amp_custom_blacklist', 100); function amp_custom_blacklist( $data ){ unset($data['AMP_Blacklist_Sanitizer']); $data[ 'AMP_New_Blacklist' ] = array(); return $data; }
After doing these steps, forms will not be stripped from the AMP Content.
But there might still be an error of action in AMP, so there are two options for this, use custom AMP Editor and change action to action-xhr or filter the content and replace the action with action-xhr.
And also need to add class name ampforwp-form-allow for sanitizing the form.
You can filter the content like this:
add_filter('the_content','new_form_content'); function new_form_content($content){ if ( function_exists( 'ampforwp_is_amp_endpoint' ) && ampforwp_is_amp_endpoint() ) { $content = preg_replace('#<form action="(.*?)" (.*?)>#ius', '<form action-xhr="$1" class="ampforwp-form-allow" $2 target="_blank">', $content); } return $content; }
You can style the forms with either custom CSS or with the hook;
This is how you can do it with the hook:
add_action('amp_post_template_css','new_css_for_form',999); function new_css_for_form(){ ?> .amp-wp-content form>div { display:none; } <?php }
Now you can add forms in AMP without any worries.
You can read more about AMP forms here: Forms in AMP
That’s it for this tutorial!
We hope it helped you. If you have any feedback or questions, then please share them in the comments section below.
Can`t activate plugin with this code:
add_action(‘amp_post_template_css’,’new_css_for_form’,999);
function new_css_for_form(){ ?>
.amp-wp-content form>div {
display:none;
}
Hi Legnum,
You need to close the function as well after writing the CSS just close the function and I am sure it will work and also you can use our custom CSS option where you no need to create any function and you can add the CSS there which works same as the hooks.
The custom plugin is now activated, but stars are not displayed with this code. Works only if i make the plugin without this code.