Last active
October 9, 2017 17:41
-
-
Save pattonwebz/fd292fcc492ae6e41fa0e159080a8949 to your computer and use it in GitHub Desktop.
How to use the filter in yoast seo to redefine a default image for only certain CPT that is used in the open graph tags.
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 | |
/** | |
* Filters the image used in social meta tags added by yoast seo plugin. | |
* | |
* This is used to set a default social share image for various post types. | |
* | |
* @param string $image string containing link to image that is used in tags. | |
* @return string string containing maybe updated url to image | |
*/ | |
function pwwp_filter_yoast_opengraph_image( $image = '' ) { | |
// make $post available in local scope. | |
global $post; | |
// this is the name of the cpt we want to modify. | |
$cpt_to_modify = 'your-cpt'; | |
// this is the id of the media library item we want to use. | |
$media_id = '33333'; | |
// this is a partial of the url to the globally defined default image. | |
$string_match = '/img/logo.php'; | |
// check we're on the post type we want to set a default image for. | |
if ( $cpt_to_modify === $post->post_type ) { | |
// if there is no featured image set it to a specfic one | |
// NOTE: there should ALWAYS be a url as there is a global default set, | |
// this is just in case there isn't. For wahatever reason. | |
if ( ! $image ) { | |
// since no image is defined set it to the media item we want. | |
$image = wp_get_attachment_url( $media_id ); | |
} else { | |
// if the image url has this partial string then it's the default | |
// and we want to override it for setting this CPTs default. | |
if ( strpos( $image, $string_match ) !== false ) { | |
// set the image to the specific media item we want. | |
$image = wp_get_attachment_url( $media_id ); | |
} | |
} | |
} | |
return $image; | |
} | |
add_filter( 'wpseo_opengraph_image', 'pwwp_filter_yoast_opengraph_image', 10, 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment