0

I came across this post which nearly does exactly what I need. But I am using a page builder and inserting into the template produces undesirable results.

I have been trying to get this snippet into a shortcode but alas, I have no idea what I'm doing. Can anyone help?

Download button for Featured Image in every post - automatically

1 Answer 1

0

You can use add_shortcode function to register a custom shortcode for your site. For example like this,

// add to (child) theme's functions.php
function my_download_featured_image_link( $atts, $content = '' ) {
  // shortcode should return its output
  return sprintf(
    '<a class="download_image" href="%s">%s</a>', // html output of the shortcode
    esc_url( get_the_post_thumbnail_url(null, 'full') ), // defaults to current global $post
    esc_html__( 'Download featured image', 'textdomain' ) // translatable anchor text
  );
}
add_shortcode( 'my_download_featured_image', 'my_download_featured_image_link' );

To use the shortcode add [my_download_featured_image] to your post content.

Alternatively you could use the_content filter to automatically add the download link at the end of the post content. The link output might require some tweaking for it to play nicely with the page builder you're using.

// add to (child) theme's functions.php
function my_download_featured_image_link_after_content( $content ) {
  if ( is_singe() || has_post_thumbnail() ) {
    return $content . sprintf(
      '<a class="download_image" href="%s">%s</a>',
      esc_url( get_the_post_thumbnail_url(null, 'full') ), 
      esc_html__( 'Download featured image', 'textdomain' )
    );
  } else {
    return $content;   
  }
}
add_filter( 'the_content', 'my_download_featured_image_link_after_content' );
2
  • Thank you so much. I used the first snippet. I really appreciate it. :-)
    – joy
    Jan 16, 2020 at 19:05
  • Nevermind, I got it. I just needed to add the word download: function download_featured_image_link( $atts, $content = '' ) { // shortcode should return its output return sprintf( '<a class="download_image" href="%s" download>%s</a>', // html output of the shortcode esc_url( get_the_post_thumbnail_url(null, 'full') ), // defaults to current global $post esc_html__( 'Download featured image', 'textdomain' ) // translatable anchor text ); } add_shortcode( 'download_featured_image', 'download_featured_image_link' );
    – joy
    Jan 16, 2020 at 19:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.