Last active
January 9, 2024 17:17
-
-
Save zackpyle/f8a10768c43e0181a395357878956806 to your computer and use it in GitHub Desktop.
Use [primary_category] to display SEOPress Primary Category
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 //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