Add Related Posts To Accelerated Mobile Pages (AMP) in WordPress

Updated so that you can choose to show the featured image for related posts on AMP.

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.

New: Step 1 gives you the choice to show only the post titles for the related posts, or to show featured images, as well. If you are showing images, also see the new Step 3.

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:

  1. To show related posts before the categories and tags, change the 1 on line 6 to 0.
  2. To show related posts after categories, tags, and the Comments button, change the 1 on line 6 to 2.
/**
 * 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
}

See more: ,

We've 29 Responses

  1. 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. πŸ˜‰

    Fabionodariphoto.com
    • 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 with amp_get_permalink( $post->ID ). You can add the CSS with the amp_post_template_css hook.

      Hope that helps.

      Isabel
  2. 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
  3. 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
    • 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:

      /**
       * Style the AMP related posts
       */
      add_action( 'amp_post_template_css', 'isa_amp_related_posts_css' );
      function isa_amp_related_posts_css( $amp_template ) {
          ?>
      	.amp-wp-tax-tag ul li {
      		white-space: nowrap;
      	}	
          <?php
      }
      

      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; }

      Isabel
  4. 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!

    Muchere
  5. 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

    Engr Obasuyi

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]