class-acf-location-nav-menu.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. if ( ! defined( 'ABSPATH' ) ) {
  3. exit; // Exit if accessed directly
  4. }
  5. if ( ! class_exists( 'ACF_Location_Nav_Menu' ) ) :
  6. class ACF_Location_Nav_Menu extends ACF_Location {
  7. /**
  8. * Initializes props.
  9. *
  10. * @date 5/03/2014
  11. * @since 5.0.0
  12. *
  13. * @param void
  14. * @return void
  15. */
  16. public function initialize() {
  17. $this->name = 'nav_menu';
  18. $this->label = __( 'Menu', 'acf' );
  19. $this->category = 'forms';
  20. $this->object_type = 'menu';
  21. }
  22. /**
  23. * Matches the provided rule against the screen args returning a bool result.
  24. *
  25. * @date 9/4/20
  26. * @since 5.9.0
  27. *
  28. * @param array $rule The location rule.
  29. * @param array $screen The screen args.
  30. * @param array $field_group The field group settings.
  31. * @return bool
  32. */
  33. public function match( $rule, $screen, $field_group ) {
  34. // Check screen args.
  35. if ( isset( $screen['nav_menu'] ) ) {
  36. $nav_menu = $screen['nav_menu'];
  37. } else {
  38. return false;
  39. }
  40. // Allow for "location/xxx" rule value.
  41. $bits = explode( '/', $rule['value'] );
  42. if ( $bits[0] === 'location' ) {
  43. $location = $bits[1];
  44. // Get the map of menu locations [location => menu_id] and update $nav_menu to a location value.
  45. $menu_locations = get_nav_menu_locations();
  46. if ( isset( $menu_locations[ $location ] ) ) {
  47. $rule['value'] = $menu_locations[ $location ];
  48. }
  49. }
  50. // Compare rule against $nav_menu.
  51. return $this->compare_to_rule( $nav_menu, $rule );
  52. }
  53. /**
  54. * Returns an array of possible values for this rule type.
  55. *
  56. * @date 9/4/20
  57. * @since 5.9.0
  58. *
  59. * @param array $rule A location rule.
  60. * @return array
  61. */
  62. public function get_values( $rule ) {
  63. $choices = array(
  64. 'all' => __( 'All', 'acf' ),
  65. );
  66. // Append locations.
  67. $nav_locations = get_registered_nav_menus();
  68. if ( $nav_locations ) {
  69. $cat = __( 'Menu Locations', 'acf' );
  70. foreach ( $nav_locations as $slug => $title ) {
  71. $choices[ $cat ][ "location/$slug" ] = $title;
  72. }
  73. }
  74. // Append menu IDs.
  75. $nav_menus = wp_get_nav_menus();
  76. if ( $nav_menus ) {
  77. $cat = __( 'Menus', 'acf' );
  78. foreach ( $nav_menus as $nav_menu ) {
  79. $choices[ $cat ][ $nav_menu->term_id ] = $nav_menu->name;
  80. }
  81. }
  82. // Return choices.
  83. return $choices;
  84. }
  85. }
  86. // Register.
  87. acf_register_location_type( 'ACF_Location_Nav_Menu' );
  88. endif; // class_exists check