0

I know this has been investigated before but no one has given a solution. Besides, I have not enough Stack-reputation to add comments, so I have to ask a new question.

I want to use a post's custom-field ("fieldname") value as featured image. I would like to create one single function-to-fit-all. I come from this, but with no luck:

add_filter('get_the_post_thumbnail', function($html) {$post = get_post();
if (! $post) { return $html; }
if (! in_array($post->post_type, array('fieldname-one', 'fieldname-two'), true)) { return $html; }
$newThumbnail = filter_var( get_post_meta($post->ID, 'fieldname-one', 'fieldname-two', true), FILTER_SANITIZE_URL );
if($newThumbnail) { $html = '<img src="' . esc_url($newThumbnail) . '" alt="" />'; }
return $html;
});

Can anyone point me to the right direction? Thank you

  • This custom image will show only front end? Will it also show on featured image section of post edit screen? – Chinmoy Kumar Paul Jan 30 at 8:41
  • What you want is possible, but it's not going to be simple. And instead of trying to make it, try to do something like: create a function which retrieves the custom field value and returns a custom featured image HTML, and then use that function instead of get_the_post_thumbnail() when retrieving the featured image. Have a good day. – Sally CJ Jan 31 at 18:15
  • how does it work here on Stack? why have the previous answers been deleted? Anyway, creating a function that retrieves the field is what I have been trying so far, with no luck. e.g.<br>add_filter('post_thumbnail_html', function($html) { $post = get_post(); if (! $post) { return $html; } if (! in_array($post->post_type, array('company'), true)) { return $html; } $newThumbnail = filter_var( get_post_meta($post->ID, 'FeaturedImage', true), FILTER_SANITIZE_URL ); if($newThumbnail) { $html = '<img src="' . esc_url($newThumbnail) . '" alt="" />'; } return $html; }); – Criss Jan 31 at 19:34
  • You say it's not simple but here's another splendid solution to the problem: pastebin.com/34WFEMXd it just doesn't work on my site: – Criss Feb 2 at 21:51
  • another one: wordpress.stackexchange.com/questions/216264/… – Criss Feb 3 at 20:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.