Get featured image thumbnail and inserting into custom field on wordpress posts


I’m not a developer so trying to put this together has not been successful. Hope someone can assist!

My goal – create a custom field on a wordpress post when a post is published or updated which contains the actual full url of the featured image (i.e. containing the .jpg or whatever extension). The url will somehow(!) then be used in Zapier to post to instagram when a new post is created in my WordPress instance.

I have found two bits of code to be added as PHP in WP Code plugin, but I don’t know how to combine them into one. First one create the custom field, second relates to creating a shortcode which isn’t needed but the main code does what it needs to by getting the actual feature image thumbnail url. I think I need to combine these somehow and add to WP Code in my wordpress site.

First create custom field:

add_action('publish_post', 'add_custom_field_automatically');
function add_custom_field_automatically($post_ID) {
    global $wpdb;
    if(!wp_is_post_revision($post_ID)) {
        add_post_meta($post_ID, 'field-name', 'custom value', true);

Second get thumbnail url (ignore that it relates to a shortcode):

function featured_img_url_shortcode() {
    global $post;
    if(has_post_thumbnail($post->ID)) {
        return get_the_post_thumbnail_url($post->ID);
    } else {
        return '';
add_shortcode('featured_img_url', 'featured_img_url_shortcode');

So I am clueless on how to create a custom field (maybe called ‘thumbnail_image_url’ and then automatically populate it with the full url…. then finally I’ll need to reference this in Zapier (which I have raised a question about here but not getting anywhere… ).

Hope that all makes sense!!

Thank you in advance!

StevieK 3 months 2023-12-09T04:40:19-05:00 0 Answers 0 views 0

Leave an answer