class-wpseo-primary-term.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO
  6. */
  7. /**
  8. * Represents a post's primary term
  9. */
  10. class WPSEO_Primary_Term {
  11. /**
  12. * @var string
  13. */
  14. protected $taxonomy_name;
  15. /**
  16. * @var int
  17. */
  18. protected $post_ID;
  19. /**
  20. * The taxonomy this term is part of
  21. *
  22. * @param string $taxonomy_name Taxonomy name for the term.
  23. * @param int $post_id Post ID for the term.
  24. */
  25. public function __construct( $taxonomy_name, $post_id ) {
  26. $this->taxonomy_name = $taxonomy_name;
  27. $this->post_ID = $post_id;
  28. }
  29. /**
  30. * Returns the primary term ID
  31. *
  32. * @return int|bool
  33. */
  34. public function get_primary_term() {
  35. $primary_term = get_post_meta( $this->post_ID, WPSEO_Meta::$meta_prefix . 'primary_' . $this->taxonomy_name, true );
  36. $terms = $this->get_terms();
  37. if ( ! in_array( $primary_term, wp_list_pluck( $terms, 'term_id' ) ) ) {
  38. $primary_term = false;
  39. }
  40. $primary_term = (int) $primary_term;
  41. return ( $primary_term ) ? ( $primary_term ) : false;
  42. }
  43. /**
  44. * Sets the new primary term ID
  45. *
  46. * @param int $new_primary_term New primary term ID.
  47. */
  48. public function set_primary_term( $new_primary_term ) {
  49. update_post_meta( $this->post_ID, WPSEO_Meta::$meta_prefix . 'primary_' . $this->taxonomy_name, $new_primary_term );
  50. }
  51. /**
  52. * Get the terms for the current post ID.
  53. * When $terms is not an array, set $terms to an array.
  54. *
  55. * @return array
  56. */
  57. protected function get_terms() {
  58. $terms = get_the_terms( $this->post_ID, $this->taxonomy_name );
  59. if ( ! is_array( $terms ) ) {
  60. $terms = array();
  61. }
  62. return $terms;
  63. }
  64. }