Last active
October 15, 2020 01:41
-
-
Save cameronjonesweb/8f270951dbf71a288965599299acc8f8 to your computer and use it in GitHub Desktop.
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 | |
function cameronjonesweb_acf_setup() { | |
acf_add_options_page( | |
array( | |
'page_title' => 'Theme Settings', | |
'menu_slug' => 'cameronjonesweb-theme-settings', | |
) | |
); | |
acf_add_local_field_group( | |
array( | |
'key' => 'group_cameronjonesweb_theme_settings', | |
'title' => 'Theme Settings', | |
'fields' => array( | |
array( | |
'key' => 'field_cameronjonesweb_default_image', | |
'label' => 'Default Featured Image', | |
'name' => 'default_featured_image', | |
'type' => 'image', | |
), | |
), | |
'location' => array ( | |
array ( | |
array ( | |
'param' => 'options_page', | |
'operator' => '==', | |
'value' => 'cameronjonesweb-theme-settings', | |
), | |
), | |
), | |
) | |
); | |
} | |
add_action( 'acf/init', 'cameronjonesweb_acf_setup' ); |
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 | |
/** | |
* @link https://wordpress.stackexchange.com/a/175179/65582 | |
* @return null|int Null if the post already has a featured image, ID of the default image if not | |
*/ | |
function cameronjonesweb_maybe_use_default_featured_image( $value, $post_id, $meta_key, $single ) { | |
// Only run on the front end. | |
if ( ! is_admin() && ! wp_is_json_request() ) { | |
// Only apply to specific post types. | |
if ( in_array( get_post_type( $post_id ), array( 'post' ) ) ) { | |
$meta_needed = '_thumbnail_id'; | |
// Only run specifically on the thumbnail meta. | |
if ( isset( $meta_key ) && $meta_needed === $meta_key ) { | |
// We need to get the meta without this function running, so we remove it all inception like. | |
remove_filter( 'get_post_metadata', 'cameronjonesweb_maybe_use_default_featured_image', 100 ); | |
// This will be the ID of the thumbnail if the post has one already. | |
$current_meta = get_post_meta( $post_id, $meta_needed, true ); | |
// Now that we have the normal value, add the function back. | |
add_filter( 'get_post_metadata', 'cameronjonesweb_maybe_use_default_featured_image', 100, 4 ); | |
// If it doesn't have a thumbnail set, inject our default image. | |
$value = ! empty( $current_meta ) ? $current_meta : get_field( 'default_featured_image', 'options', false ); | |
} | |
} | |
} | |
return $value; | |
} | |
add_filter( 'get_post_metadata', 'cameronjonesweb_maybe_use_default_featured_image', 100, 4 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment