This is how to add related posts to your Accelerated Mobile Pages (AMP). This is only for those of you using the WordPress AMP plugin (by Automattic) for Accelerated Mobile Pages. The WP AMP plugin displays your AMP pages with a minimalistic template for single AMP posts. It has no menu, and no related posts.
The AMP plugin added a footer in version 0.4. To add related posts under each AMP post, but above the footer, follow these steps.
Works on Custom Post Types
If you’ve added AMP support to a custom post type, then this will show related posts on that custom post type, as well, IF that post type supports a taxonomy. If you’ve added a custom taxonomy for that custom post type, then the related posts will be posts of that same custom taxonomy terms.
So, this works both on regular posts and custom post types that support AMP. Related posts will be selected first by matching tag. If no post exists with a matching tag, then it will select related posts by category or by custom taxonomy.
Showing only titles without images will keep it light and accelerated (Accelerated Mobile Pages, right?). The first example just shows related posts as an unordered list of links. No featured images or excerpts. The link text will be the post title. This will also show a heading, “You May Also Like,” above the related posts. You can change this heading on line 58 in the first code block, or line 60 in the second code block.
By default, this adds two related posts. If you want to list more or less than two, you can change the 2
to whatever number you like on line 12 in the first code block, or line 14 in the second code block.
Step 1: Create a Template File For Related Posts
Create a folder in your theme called amp
which you may already have if you’ve customized any AMP template parts. This should be in your child theme, if you’re using one. In this amp
folder, add a new file called related-posts.php
.
In that file, paste one of the next 2 code blocks.
If you want related posts to show only the titles, then use this:
<?php if ( ! is_single() ) { return; } global $post; $taxs = get_object_taxonomies( $post ); if ( ! $taxs ) { return; } $count = 2; // ignoring post formats if( ( $key = array_search( 'post_format', $taxs ) ) !== false ) { unset( $taxs[$key] ); } // try tags first if ( ( $tag_key = array_search( 'post_tag', $taxs ) ) !== false ) { $tax = 'post_tag'; $tax_term_ids = wp_get_object_terms( $post->ID, $tax, array( 'fields' => 'ids' ) ); } // if no tags, then by cat or custom tax if ( empty( $tax_term_ids ) ) { // remove post_tag to leave only the category or custom tax if ( $tag_key !== false ) { unset( $taxs[ $tag_key ] ); $taxs = array_values($taxs); } $tax = $taxs[0]; $tax_term_ids = wp_get_object_terms( $post->ID, $tax, array('fields' => 'ids') ); } if ( $tax_term_ids ) { $args = array( 'post_type' => $post->post_type, 'posts_per_page' => $count, 'orderby' => 'rand', 'tax_query' => array( array( 'taxonomy' => $tax, 'field' => 'id', 'terms' => $tax_term_ids ) ), 'post__not_in' => array ($post->ID), ); $related = get_posts( $args ); if ( $related ) { ?> <div class="amp-wp-meta amp-wp-tax-tag"> <h3>You May Also Like</h3> <ul> <?php foreach( $related as $post) { setup_postdata( $post ); ?> <li><a href="<?php echo esc_url( amp_get_permalink( get_the_id() ) ); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li> <?php } ?> </ul> </div> <?php } wp_reset_postdata(); } ?>
If you want related posts to show the featured image next to the title, then use the next code instead of the one above.
Note that the image size on line 12, below, is set to 50 pixels by 50 pixels. You can change that to the image size of your choice, in which the first number is the maximum image width and second number is the maximum image height. You can also replace the array with an existing image size, for example, you could change line 12 to
$size = 'thumbnail';
… but that may be to large to fit with the titles.
<?php if ( ! is_single() ) { return; } global $post; $taxs = get_object_taxonomies( $post ); if ( ! $taxs ) { return; } $size = array( 50, 50 ); $count = 2; // ignoring post formats if( ( $key = array_search( 'post_format', $taxs ) ) !== false ) { unset( $taxs[$key] ); } // try tags first if ( ( $tag_key = array_search( 'post_tag', $taxs ) ) !== false ) { $tax = 'post_tag'; $tax_term_ids = wp_get_object_terms( $post->ID, $tax, array( 'fields' => 'ids' ) ); } // if no tags, then by cat or custom tax if ( empty( $tax_term_ids ) ) { // remove post_tag to leave only the category or custom tax if ( $tag_key !== false ) { unset( $taxs[ $tag_key ] ); $taxs = array_values($taxs); } $tax = $taxs[0]; $tax_term_ids = wp_get_object_terms( $post->ID, $tax, array('fields' => 'ids') ); } if ( $tax_term_ids ) { $args = array( 'post_type' => $post->post_type, 'posts_per_page' => $count, 'orderby' => 'rand', 'tax_query' => array( array( 'taxonomy' => $tax, 'field' => 'id', 'terms' => $tax_term_ids ) ), 'post__not_in' => array ($post->ID), ); $related = get_posts( $args ); if ( $related ) { ?> <div class="amp-wp-meta amp-wp-tax-tag"> <h3>You May Also Like</h3> <div id="amp-related-posts"> <?php foreach( $related as $post) { setup_postdata( $post ); ?> <p><a href="<?php echo esc_url( amp_get_permalink( get_the_id() ) ); ?>"><?php $thumb_id = get_post_thumbnail_id( $post->ID ); if ( $thumb_id ) { $img = wp_get_attachment_image_src( $thumb_id, $size ); $alt = get_post_meta( $post->ID, '_wp_attachment_image_alt', true ); if ( empty( $alt ) ) { $attachment = get_post( $thumb_id ); $alt = trim(strip_tags( $attachment->post_title ) ); } ?> <amp-img class="related-img" src="<?php echo esc_url( $img[0] ); ?>" <?php if ( $img_srcset = wp_get_attachment_image_srcset( $thumb_id, $size ) ) { ?> srcset="<?php echo esc_attr( $img_srcset ); ?>" <?php } ?> alt="<?php echo esc_attr( $alt ); ?>" width="<?php echo $img[1]; ?>" height="<?php echo $img[2]; ?>"> </amp-img> <?php } ?> <span><?php the_title(); ?></span></a></p> <?php } ?> </div> </div> <?php } wp_reset_postdata(); } ?>
Step 2: Functions
Add the following to your functions (see how to add functions).
The first function adds related posts to the post footer parts. By default, since version 0.4, AMP shows categories, tags, and a big “Comments” button under each post.
This adds related posts after categories and tags, but before the big Comments button. You have two other choices:
- To show related posts before the categories and tags, change the
1
on line 6 to0
. - To show related posts after categories, tags, and the Comments button, change the
1
on line 6 to2
.
/** * Add related posts to AMP amp_post_article_footer_meta */ function my_amp_post_article_footer_meta( $parts ) { $index = 1; array_splice( $parts, $index, 0, array( 'my-related-posts' ) ); return $parts; } add_filter( 'amp_post_article_footer_meta', 'my_amp_post_article_footer_meta' ); /** * Designate the template file for related posts */ function my_amp_related_posts_path( $file, $template_type, $post ) { if ( 'my-related-posts' === $template_type ) { $file = get_stylesheet_directory() . '/amp/related-posts.php'; } return $file; } add_filter( 'amp_post_template_file', 'my_amp_related_posts_path', 10, 3 );
Step 3: Only If Showing Images For Related Posts
This step is only needed if you have chosen to show the featured images with your related posts (if you used the second code from Step 1). You should add the following to your functions. This adds some style to align your images. You can insert more CSS styles into line 11, if you need more style customizations.
/** * Style to align the AMP related posts images */ add_action( 'amp_post_template_css', 'isa_amp_css_styles_fonts' ); function isa_amp_css_styles_fonts( $amp_template ) { ?> #amp-related-posts p amp-img { margin-right:1em; vertical-align: middle; } <?php }
Fabionodariphoto.com
February 26th, 2016 at 2:23 am
Hi Isabel.
I added the code and it works great.Thank you.. π
Just two small bugs (or maybe it’s just me):
1) the related posts links are shown on the left side not in the center.
2) the related links are not AMP. When you click the link it will open a regular post.
Don’t know if it’s clear. You can check this for example and click on a related post:
Last question..
What plugin can I use to show the Social Share Icon on AMP posts? I’m using Shareaholic but I’m sick and tired of it. It’s slowing down the blog and loads “partner” links without my permission. Plus the icons don’t work on AMP posts… So I want to use something simple that works also on AMP.
Thanks a lot for your help and amazing tips… Keep up the good work Isabel. π
Isabel
February 26th, 2016 at 3:36 pm
1. Thank you for the heads up. The latest release of the AMP plugin changed the CSS class from “content” to “amp-wp-content”. I just updated the code above, so the related posts will now be centered again.
2. I just updated line 66 in the code to link to the AMP URL instead of the regular post permalink.
3. These social sharing links work well on AMP. You can insert the HTML into the code above, right after the closing div on line 87. But, in order to share the AMP URL instead of the regular URL, replace the 3 instances of
get_permalink
withamp_get_permalink( $post->ID )
. You can add the CSS with theamp_post_template_css
hook.Hope that helps.
kdpuvvadi
February 26th, 2016 at 9:41 am
it is directly giving direct links, what if i want add amp links for related posts?
Isabel
February 26th, 2016 at 3:38 pm
Hi, I just updated the code to link the AMP url instead.
Gene
March 24th, 2016 at 3:05 pm
Hello, thank you for this post. I have a website that is updated daily and the related posts show links from last year. Is it possible to tweak that so that related posts can show from the last few days?
Gene
March 24th, 2016 at 3:29 pm
I was able to fix my issue by changing ‘orderby’ => ‘rand’, to ‘orderby’ => ‘desc’,
How do I remove the /amp so I can have links direct to the main non-amp page?
Gene
March 24th, 2016 at 7:35 pm
Sorry, fixed my last issue too.
I replaced amp_get_permalink with get_permalink
Thanks! π
niammuddin
July 25th, 2016 at 4:12 am
thanks, how to add share fb twitter and more to AMP wordpress pages? please help me.
Isabel
July 27th, 2016 at 11:51 pm
Please see: Social Media Share Buttons For AMP (Accelerated Mobile Pages). Hope that helps.
abhay
February 21st, 2017 at 12:51 pm
if you can tell me how to add related posts with thumbnail that would be great..
its work but i want the thumbnail images with it
Isabel
February 21st, 2017 at 8:16 pm
I just updated this to include the code for adding the thumbnail images.
abhay
February 22nd, 2017 at 11:44 am
Thanks for adding this .. its perfectly fine the way I wanted.
but its not showing on most of the pages, showing only in few ..
tell me whats wrong i did ?
and also if you can add the codes for floating sharing button that would be awesome
Isabel
February 22nd, 2017 at 1:41 pm
On the pages that it’s not showing, do those pages have a tag or category? Are there other posts in that tag or category? If there are no other posts in that tag or category, then nothing will show.
abhay
February 22nd, 2017 at 11:48 pm
its fine now .. that was caching problem
Denis
February 26th, 2017 at 12:57 pm
Hi,
thx for the nice tutorial. last question π
How can I change the related post titel length, so that no linebreaks happen?
Thx
Isabel
February 27th, 2017 at 12:40 am
If you are you showing the related posts without images, you can force the titles to not wrap by adding this to your functions:
Or, if you are showing them with the featured images, then just insert this line into line 11 of Step 3, above:
#amp-related-posts a span { white-space: nowrap; }
King
April 18th, 2017 at 11:45 pm
Is this gonna work on a custom post type?
Isabel
April 19th, 2017 at 1:13 am
Yes.
Udegbunam Chukwudi
June 22nd, 2017 at 4:09 pm
Thanks. It worked for me with a few css tweaks
Muchere
July 14th, 2017 at 1:26 pm
Sorry to ask about this on this post, I want to ask about multipaged content pagination on AMP but I can’t find anything about this on your website.
I have a lot of long posts and I’m using pagination to split it up, but Automattic AMP plugin don’t support post pagination (usually called using ). Is there a way to make it happen? I tried for 2 days but can’t make it work, usually I did modify plugin and theme here and there, a simple one, but never on core level.
Thanks for the help!
WaleRazaq
June 1st, 2018 at 3:26 pm
Hi. I’d like to display 3 related posts per page instead of 2. Can I just change $count to 3?
Isabel
June 1st, 2018 at 3:39 pm
Yes, you can change the 2 to 3 (or whatever number you like) on line 12 in the first code block, or line 14 in the second code block.
WaleRazaq
June 1st, 2018 at 5:48 pm
Thanks.
Saipul Muiz
August 4th, 2018 at 10:29 am
Thanks for help me.. This code work for me!
Sanjay Kumar Monu
August 20th, 2019 at 12:58 am
How to Remove Site Icon From the Header of AMP Pages?
You can check the amp pages of my website to know what I am talking about.
Isabel
August 25th, 2019 at 2:47 pm
See How to Remove Site Icon From the Header of AMP Pages.
Sanjay Kumar Monu
October 17th, 2019 at 2:10 pm
Yippee That Works…Thanks a Lot.
Matias LO
September 13th, 2019 at 2:24 pm
Great, thank so much
I was looking for it so much time
Thanks again
Engr Obasuyi
December 17th, 2019 at 9:35 am
Hello, thanks for this. My question is, Is the related post by Tag or by Category?….
whatsoever itβs, how can we change it to the other way?
Thanks