class-wpseo-primary-term.php 1.6 KB

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