Skip to content

Instantly share code, notes, and snippets.

@mattradford
Last active November 12, 2021 17:36
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 mattradford/da190fba9d308b16145468c38095c649 to your computer and use it in GitHub Desktop.
Save mattradford/da190fba9d308b16145468c38095c649 to your computer and use it in GitHub Desktop.
Yoast Primary and Secondary Terms
<?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;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment