class-woocommerce-shop-page.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Frontend
  6. */
  7. /**
  8. * Represents the logic to determine if the current page is a WooCommerce shop page.
  9. */
  10. class WPSEO_WooCommerce_Shop_Page implements WPSEO_WordPress_Integration {
  11. /**
  12. * Holds the shop page id.
  13. *
  14. * @var int
  15. */
  16. protected static $shop_page_id;
  17. /**
  18. * True when current page is the shop page.
  19. *
  20. * @var bool
  21. */
  22. protected static $is_shop_page;
  23. /**
  24. * Registers the hooks.
  25. *
  26. * @return void
  27. */
  28. public function register_hooks() {
  29. if ( ! $this->is_woocommerce_active() ) {
  30. return;
  31. }
  32. add_filter( 'wpseo_frontend_page_type_simple_page_id', [ $this, 'get_page_id' ] );
  33. }
  34. /**
  35. * Determines whether or not WooCommerce is active.
  36. *
  37. * @return bool True if woocommerce plugin is active.
  38. */
  39. private function is_woocommerce_active() {
  40. return WPSEO_Utils::is_woocommerce_active();
  41. }
  42. /**
  43. * Returns the ID of the WooCommerce shop page when the currently opened page is the shop page.
  44. *
  45. * @param int $page_id The page id.
  46. *
  47. * @return int The Page ID of the shop.
  48. */
  49. public function get_page_id( $page_id ) {
  50. if ( ! $this->is_shop_page() ) {
  51. return $page_id;
  52. }
  53. return $this->get_shop_page_id();
  54. }
  55. /**
  56. * Checks if the current page is the shop page.
  57. *
  58. * @return bool Whether the current page is the WooCommerce shop page.
  59. */
  60. public function is_shop_page() {
  61. global $wp_query;
  62. // Prevents too early "caching".
  63. if ( ! isset( $wp_query ) ) {
  64. return false;
  65. }
  66. if ( ! isset( self::$is_shop_page ) ) {
  67. self::$is_shop_page = $this->is_woocommerce_active() && is_shop() && ! is_search();
  68. }
  69. return self::$is_shop_page;
  70. }
  71. /**
  72. * Returns the id of the set WooCommerce shop page.
  73. *
  74. * @return int The ID of the set page.
  75. */
  76. public function get_shop_page_id() {
  77. if ( ! isset( self::$shop_page_id ) ) {
  78. self::$shop_page_id = function_exists( 'wc_get_page_id' ) ? wc_get_page_id( 'shop' ) : ( -1 );
  79. }
  80. return self::$shop_page_id;
  81. }
  82. }