class-primary-category.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Frontend
  6. */
  7. /**
  8. * Adds customizations to the front end for the primary category.
  9. */
  10. class WPSEO_Frontend_Primary_Category implements WPSEO_WordPress_Integration {
  11. /**
  12. * Registers the hooks necessary for correct primary category behaviour.
  13. */
  14. public function register_hooks() {
  15. add_filter( 'post_link_category', [ $this, 'post_link_category' ], 10, 3 );
  16. }
  17. /**
  18. * Filters post_link_category to change the category to the chosen category by the user.
  19. *
  20. * @param stdClass $category The category that is now used for the post link.
  21. * @param array $categories This parameter is not used.
  22. * @param WP_Post $post The post in question.
  23. *
  24. * @return array|null|object|WP_Error The category we want to use for the post link.
  25. */
  26. public function post_link_category( $category, $categories = null, $post = null ) {
  27. $post = get_post( $post );
  28. $primary_category = $this->get_primary_category( $post );
  29. if ( false !== $primary_category && $primary_category !== $category->cat_ID ) {
  30. $category = $this->get_category( $primary_category );
  31. }
  32. return $category;
  33. }
  34. /**
  35. * Get the id of the primary category.
  36. *
  37. * @param WP_Post $post The post in question.
  38. *
  39. * @return int Primary category id.
  40. */
  41. protected function get_primary_category( $post = null ) {
  42. $post = get_post( $post );
  43. if ( $post === null ) {
  44. return false;
  45. }
  46. $primary_term = new WPSEO_Primary_Term( 'category', $post->ID );
  47. return $primary_term->get_primary_term();
  48. }
  49. /**
  50. * Wrapper for get category to make mocking easier.
  51. *
  52. * @param int $primary_category ID of primary category.
  53. *
  54. * @return array|null|object|WP_Error
  55. */
  56. protected function get_category( $primary_category ) {
  57. $category = get_category( $primary_category );
  58. return $category;
  59. }
  60. }