• Resolved timothy12

    (@timothy12)


    I have this code snippet

    <?php
    // Import necessary libraries
    require_once('wp-load.php');

    $post_id = get_the_ID(); // Get the current post ID
    $primary_category = get_post_meta($post_id, '_yoast_wpseo_primary_category', true);
    $categories = get_the_category($post_id);

    if ($primary_category === 'Prezi' || $primary_category === 'Kahoot') {
    echo 'A';
    } elseif (count($categories) === 1 && ($categories[0]->slug === 'Prezi' || $categories[0]->slug === 'Kahoot')) {
    echo 'B';
    } else {
    echo 'C';
    }
    ?>

    What it should do (and doesn’t at the moment)

    is getting the primary category of the post. That primary category is created by the Yoas SEO plugin. When the primary category is “Prezi” or “Kahoot”, it should echo ‘A’. Wanneer there is just one category selected (and the isn’t a primary one) and that category is either “Prezi” or “Kahoot”, it should echo dan ‘B’. If the category isn’t “Prezi” or”Kahoot”, ‘C’ should be echoed.

    In my case, only ‘C’ is echoed, while that categories in the posts are properly set. Is there an error in the code I don’t see?

    Earlier, I had this code snippet, but is showed the parent category, always the first selected category of a post. If this code snippet could be adapted by getting the primary category and echoing ‘A’ of ‘C’, I’m happy too. Part ‘B’ isn’t that important.

    <?php
    $post_categories = get_the_category($post->ID);
    $parent_category_name = '';

    if (!empty($post_categories)) {
    $parent_category = $post_categories[0]->parent ? get_category($post_categories[0]->parent) : $post_categories[0];
    $parent_category_name = $parent_category->name;
    }

    if ($parent_category_name === 'Prezi' || $parent_category_name === 'Kahoot') {

    echo
    "<span>A</span>";
    }
    else
    {
    echo "<span>C</span>";
    }
    ?>

Viewing 1 replies (of 1 total)
  • Thread Starter timothy12

    (@timothy12)

    With the following code snippet I got it working as I wanted. Thanks for your tip! The option B also works when there is just one single category selected. It automatically becomes the primary category,

    <?php                                                

    $primary_term_id = yoast_get_primary_term_id( 'category', $post_id );

    $term = get_term( $primary_term_id ); // Get the term object to access its name

    if ( $term->name == 'Prezi' || $term->name == 'Kahoot' ) {

        echo "Lolly.";

    } else {

        echo "Zuurstok";

    }

    ?>       
Viewing 1 replies (of 1 total)

The topic ‘Echo content based on primary category’ is closed to new replies.