How to get the name of the primary category of a post in WordPress

To get the name of the primary category of a post, you’ll need to use the Yoast SEO plugin, as WordPress does not have a native “primary category” feature.

Once you have Yoast SEO installed and activated, you can use the following code to get the primary category name:

// Check if Yoast SEO plugin is active
if (class_exists('WPSEO_Primary_Term')) {
    // Get the post ID (you can replace this with a specific post ID if needed)
    $post_id = get_the_ID();

    // Get the primary category ID
    $wpseo_primary_term = new WPSEO_Primary_Term('category', $post_id);
    $primary_term_id = $wpseo_primary_term->get_primary_term();

    // Get the primary category object
    $primary_category = get_term($primary_term_id);

    // Check if the primary category object is valid
    if (!is_wp_error($primary_category)) {
        // Get the primary category name
        $primary_category_name = $primary_category->name;

        // Display the primary category name
        echo 'Primary Category: ' . $primary_category_name;
    } else {
        echo 'No primary category found.';
    }
} else {
    echo 'Yoast SEO plugin is not active.';
}

You can add this code snippet to your WordPress theme’s template files where you want to display the primary category name. This code will check if the Yoast SEO plugin is active and then fetch the primary category name for the current post or a specific post ID.

Remember to always backup your files before making any changes, and test your changes on a staging site or local development environment before applying them to your live site.

If you don’t use the Yoast SEO plugin and simply want to fetch the first category assigned to the post, you can use the following code:

// Get the post ID (you can replace this with a specific post ID if needed)
$post_id = get_the_ID();

// Get the post categories
$categories = get_the_category($post_id);

// Check if there are any categories
if (!empty($categories)) {
    // Get the first category's name
    $first_category_name = $categories[0]->name;

    // Display the first category name
    echo 'First Category: ' . $first_category_name;
} else {
    echo 'No categories found.';
}

Leave a Reply

Your email address will not be published. Required fields are marked *