Last active
September 12, 2018 10:44
-
-
Save paaljoachim/857644243e033668101615e14d85bb69 to your computer and use it in GitHub Desktop.
Set Featured image. 1. Sets the featured image. 2. If no featured image get image from category. 3. If no category image then get the first post image. 4. If no post image or category image then sets a fallback image.
This file contains 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
// Inside your functions file add the following code | |
// | |
function wpforce_featured() { | |
global $post; | |
$already_has_thumb = has_post_thumbnail($post->ID); // If post have a featured image use that. | |
if (!$already_has_thumb) { | |
// If post does not have a featured image then get the first post image and set as featured image. | |
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" ); // Number 1 relates to taking post image number 1 and adding it as a featured image. | |
if ($attached_image) { | |
foreach ($attached_image as $attachment_id => $attachment) { | |
set_post_thumbnail($post->ID, $attachment_id); | |
//$attachment_id = attachment_url_to_postid( $image_url ); | |
// echo $attachment_id; | |
} | |
} else if ( in_category('WordPress') ){ // Add your own categories. | |
set_post_thumbnail($post->ID, '21'); | |
// Find attachment media id by right clicking the image in the Media library and selecting inspect element. Look for the data-id number. This number is then added to the post id. | |
} | |
else if ( in_category('test') ) { | |
set_post_thumbnail($post->ID, '30'); | |
} | |
else if ( in_category('images') ) { | |
set_post_thumbnail($post->ID, '111'); | |
} | |
else if ( in_category('Uncategorized') ) { | |
set_post_thumbnail($post->ID, '111'); | |
} | |
} | |
} //end function | |
add_action('the_post', 'wpforce_featured'); | |
add_action('save_post', 'wpforce_featured'); | |
add_action('draft_to_publish', 'wpforce_featured'); | |
add_action('new_to_publish', 'wpforce_featured'); | |
add_action('pending_to_publish', 'wpforce_featured'); | |
add_action('future_to_publish', 'wpforce_featured'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is a bit glicthy... during testing the browser Chrome/Firefox did not refresh after a code change. I had to use code to remove featured images and then test another piece of code. This did not happen with the Genesis featured image code snippet.
https://gist.github.com/paaljoachim/2adcc2fc7eae059d5be47a4ccb77aa86
What I want to do is add code to the Genesis snippet so that it can be added to a functions file for most themes not just Genesis themes.