The following script will add the schema markup in existing RankMath SEO plugins JSON-LD based on the post category.
The script will look up the category of the post and then inject the schema data according to it.
// tested at browserhow.com for chrome and edge categories //
function custom_json_ld_for_categories($data) {
// Get the current post ID
$post_id = get_the_ID();
// Get the categories associated with the post
$categories = get_the_category($post_id);
// Check if any category matches the specified slugs for Chrome or Edge
$chrome_slugs = array('chrome', 'chrome-android', 'chrome-ios', 'chrome-computer');
$edge_slugs = array('edge', 'edge-ios', 'edge-computer');
$matched_chrome_categories = array_filter($categories, function($category) use ($chrome_slugs) {
return in_array($category->slug, $chrome_slugs);
});
$matched_edge_categories = array_filter($categories, function($category) use ($edge_slugs) {
return in_array($category->slug, $edge_slugs);
});
// If there are matched categories, build the JSON-LD data
if (!empty($matched_chrome_categories)) {
$json_ld_data = array(
"about" => array(
array(
"@type" => "Thing",
"name" => "Google Chrome",
"sameAs" => [ "https://www.google.com/chrome/",
"https://en.wikipedia.org/wiki/Google_Chrome",
"https://wikidata.org/wiki/Q777" ]
),
)
);
// Merge the custom JSON-LD data with the existing RankMath data
$data = array_merge($data, $json_ld_data);
} elseif (!empty($matched_edge_categories)) {
$json_ld_data = array(
"about" => array(
array(
"@type" => "Thing",
"name" => "Microsoft Edge",
"sameAs" => [ "https://www.microsoft.com/edge/",
"https://en.wikipedia.org/wiki/Microsoft_Edge",
"https://wikidata.org/wiki/Q18698690" ]
),
)
);
// Merge the custom JSON-LD data with the existing RankMath data
$data = array_merge($data, $json_ld_data);
}
return $data;
}
// Hook into the 'rank_math/json_ld' filter to add custom JSON-LD data
add_filter('rank_math/json_ld', 'custom_json_ld_for_categories');
Idea source: https://searchengineland.com/entities-seo-schema-google-content-428602