Az mantık yürütelim ,
Eğer öne çıkan görsel yoksa, siz bir resmi öne çıakrılan görselmiş gibi davranmasını mı istiyorsunuz yazı içindeki ?
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
// no image found display default image instead
if(empty($first_img)){
$first_img = "/images/default.jpg";
}
return $first_img;
}
function wpares__set_featured_image_on_save($post_id){
$attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC'));
if(sizeof($attachments) > 0){
set_post_thumbnail($post_id, $attachments[0]->ID);
}else{
// definning required libs. wp core.
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
// load the images (core.)
$img = catch_that_image();
if ("/images/default.jpg" != $img){
$result = media_sideload_image($img, $post_id);
$attachments = get_posts(array('numberposts' => '1', 'post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC'));
if(sizeof($attachments) > 0)
set_post_thumbnail($post_id, $attachments[0]->ID);
}else{
//no images found
return;
}
}
}
add_action( 'save_post', 'wpares__set_featured_image_on_save' );
function auto_set_post_image( $post_id ) {
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// Check permissions
if ( 'page' == $_POST['post_type'] ){
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}else{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
// need to find and save the data
//check if we have a post thumnail set already
$attch = get_post_meta($post_id,"_thumbnail_id",true);
if (empty($attch)){
set_featured_image_on_save($post_id);
}
}Resmi alıp post_save olduğunda action eklemiş olduk burada.
Fonksiyonu da temanızın functions.php sine yapıştırın.
Afiyet olsun.