Last active
November 12, 2021 17:36
-
-
Save mattradford/da190fba9d308b16145468c38095c649 to your computer and use it in GitHub Desktop.
Yoast Primary and Secondary Terms
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 | |
/** | |
* 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 <[email protected]> | |
* @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