Mark Posts in a Category as NewsArticle in Yoast
Switches the Yoast SEO Article schema type to NewsArticle for posts in the categories you list, which suits news and press sections.
Opens WPIDE on
Code
// Category slugs whose posts are news articles.
$wpide_news_categories = array( 'news', 'press' );
add_filter( 'wpseo_schema_article_type', function ( $type, $indexable = null ) use ( $wpide_news_categories ) {
$post_id = ( is_object( $indexable ) && isset( $indexable->object_type, $indexable->object_id ) && 'post' === $indexable->object_type ) ? (int) $indexable->object_id : ( is_singular() ? get_queried_object_id() : 0 );
if ( $post_id && 'post' === get_post_type( $post_id ) && has_category( $wpide_news_categories, $post_id ) ) {
return 'NewsArticle';
}
return $type;
}, 10, 2 );
Notes
Use category slugs. Other posts keep the type set in Yoast's settings.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.