Last active
November 9, 2018 15:58
-
-
Save damiencarbery/6247f69025b3db90a3b0669ecd11b01e to your computer and use it in GitHub Desktop.
Set Featured Image based on post category - As the post is saved, set the featured image based on the post category: https://www.damiencarbery.com/2018/11/set-featured-image-based-on-post-category/
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
<?php | |
/* | |
Plugin Name: Set Featured Image based on post category | |
Plugin URI: https://www.damiencarbery.com/2018/11/set-featured-image-based-on-post-category/ | |
Description: As the post is saved, set the featured image based on the post category. | |
Author: Damien Carbery | |
Author URI: https://www.damiencarbery.com | |
Version: 0.1 | |
*/ | |
// As the post is saved, set the featured image based on the post category. | |
add_action( 'save_post', 'dcwd_set_post_featured_image_on_save' ); | |
function dcwd_set_post_featured_image_on_save( $post_id ) { | |
// Only set featured image for posts. | |
if ( 'post' != get_post_type( $post_id ) ) { | |
return; | |
} | |
// List the ID of the featured image for each category. | |
$category_to_post_thumbnail = array ( 'family-focus' => 3022, 'tailored-training' => 3024 ); | |
// Skip if featured image already set. | |
if ( ! has_post_thumbnail() ) { | |
// Extract the category slugs from the returned list. | |
$post_categories = wp_list_pluck( get_the_category( $post_id ), 'slug' ); | |
foreach ( $post_categories as $post_category ) { | |
if ( array_key_exists( $post_category, $category_to_post_thumbnail ) ) { | |
set_post_thumbnail( $post_id, $category_to_post_thumbnail[ $post_category ] ); | |
break; // Set featured image based on the first match found. | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment