Skip to content

Instantly share code, notes, and snippets.

@zackpyle
Last active January 9, 2024 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zackpyle/f8a10768c43e0181a395357878956806 to your computer and use it in GitHub Desktop.
Save zackpyle/f8a10768c43e0181a395357878956806 to your computer and use it in GitHub Desktop.
Use [primary_category] to display SEOPress Primary Category
<?php //ignore this line - for gist formatting
function get_primary_category_name() {
// Get the post ID of the current page
$post_id = get_the_ID();
$cat_id = get_post_meta($post_id, '_seopress_robots_primary_cat', true);
// Validate and get the category name
if (!empty($cat_id)) {
$term = get_term($cat_id, 'category');
if (!is_wp_error($term) && !is_null($term)) {
return $term->name;
}
}
// Fallback - Fetch the first category if a primary category is not set or is invalid
$categories = get_the_category($post_id);
if (!empty($categories) && !is_wp_error($categories)) {
foreach ($categories as $category) {
if (!empty($category->name)) {
return $category->name;
}
}
}
return; // Return null if no categories found
}
add_shortcode('primary_category', 'get_primary_category_name');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment