Skip to content

Instantly share code, notes, and snippets.

@mattradford
Last active November 12, 2021 17:36
Show Gist options
  • Select an option

  • Save mattradford/da190fba9d308b16145468c38095c649 to your computer and use it in GitHub Desktop.

Select an option

Save mattradford/da190fba9d308b16145468c38095c649 to your computer and use it in GitHub Desktop.

Revisions

  1. mattradford revised this gist Nov 12, 2021. No changes.
  2. mattradford created this gist Nov 12, 2021.
    83 changes: 83 additions & 0 deletions yoast-primary-and-secondary.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,83 @@
    <?php

    /**
    * Post Categories
    *
    * Get Primary term, if set, and other terms for a post (with Primary Term excluded)
    *
    * @category Theme
    * @package MattRadford/mattradford
    * @author Matt Radford <matt@mattrad.uk>
    * @license https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html GPL-2.0+
    * @link https://github.com/10degrees/10degrees-base
    * @since 2.0.0
    */
    class PostCategories
    {
    /**
    * Post ID
    */
    public int $postID;

    /**
    * Primary Term
    */
    public object $primaryTerm;

    /**
    * Secondary Terms
    */
    public array $secondaryTerms;

    /**
    * Constructor
    */
    public function __construct($postID)
    {
    $this->postID = $postID;
    $this->getYoastPrimaryTerm();
    $this->getAllSecondaryTerms();
    }

    /**
    * Get Yoast Primary Category
    *
    * @return object $primaryTerm
    */
    public function getYoastPrimaryTerm()
    {
    if (class_exists('WPSEO_Primary_Term')) {
    $wpseoPrimaryTerm = new \WPSEO_Primary_Term('category', $this->postID);
    $wpseoPrimaryTerm = $wpseoPrimaryTerm->get_primary_term();
    $term = get_term($wpseoPrimaryTerm);
    if (!is_wp_error($term)) {
    $this->primaryTerm = $term;
    }
    }
    }

    /**
    * Get assigned Categories, exclude Primary if set
    *
    * @return object $primaryTerm
    */
    public function getAllSecondaryTerms()
    {
    $this->secondaryTerms = get_the_terms($this->postID, 'category');
    if (!class_exists('WPSEO_Primary_Term')) {
    return;
    } else {
    if ($this->primaryTerm !== null) {
    $allTerms = $this->secondaryTerms;
    $primaryTermId = $this->primaryTerm->term_id;
    $allTermIds = array_column($allTerms, 'term_id');
    if (\in_array($primaryTermId, $allTermIds)) {
    if (($key = array_search($primaryTermId, array_column($allTerms, 'term_id'))) !== false) {
    unset($allTerms[$key]);
    $this->secondaryTerms = $allTerms;
    }
    }
    }
    }
    }
    }