Created
November 15, 2018 08:23
-
-
Save saroarhossain57/14106f16567377f76c5fad451655609f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$args = array( | |
'post_type' => 'article', | |
'numberposts' => -1, | |
'post_status' => 'publish', | |
); | |
// Getting the posts | |
$articles = get_posts($args); | |
foreach ($articles as $key => $article) { | |
// Find the first image | |
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $article->post_content, $matches); | |
// Remove the image size attribute from image url | |
$pattern = "~-\d+[Xx]\d+~"; | |
$replacement = ""; | |
$new_url = preg_replace($pattern, $replacement, $matches[1][0]); | |
// Check if post don't has any featured image and the post content has any image | |
if(! has_post_thumbnail($article->ID) && !empty($new_url)){ | |
// Getting the attachment id from image url | |
$thumb_id = child_get_image_id($new_url); | |
// Finally set the attachment a featured image of that post | |
set_post_thumbnail($article->ID, (int)$thumb_id); | |
} | |
} | |
// Getting the attachmentt id from image url | |
function child_get_image_id($image_url) { | |
global $wpdb; | |
$attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); | |
return $attachment[0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment