Skip to content

Instantly share code, notes, and snippets.

@PauliusKrutkis
Created July 6, 2017 13:35
Show Gist options
  • Save PauliusKrutkis/ee8c37b07da238e1a74ac252e1b727f4 to your computer and use it in GitHub Desktop.
Save PauliusKrutkis/ee8c37b07da238e1a74ac252e1b727f4 to your computer and use it in GitHub Desktop.
Wordpress set post thumbnail with media_sideload_image function
<?php
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
$url = 'http://wordpress.org/about/images/logos/wordpress-logo-stacked-rgb.png';
$title = "Anything you want";
$postId = 1;
function setPostAttachment($attId)
{
$att = get_post($attId);
$postId = $att->post_parent;
set_post_thumbnail($postId, $attId); // set as post thumbnail
update_field('image', $att->ID, $postId); // update acf field
}
add_action('add_attachment', 'setPostAttachment');
media_sideload_image($url, $postId, $title);
remove_action('add_attachment', 'setPostAttachment');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment