class-wpseo-custom-fields.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO
  6. */
  7. /**
  8. * WPSEO_Custom_Fields.
  9. */
  10. class WPSEO_Custom_Fields {
  11. /**
  12. * Custom fields cache.
  13. *
  14. * @var array
  15. */
  16. protected static $custom_fields = null;
  17. /**
  18. * Retrieves the custom field names as an array.
  19. *
  20. * @link WordPress core: wp-admin/includes/template.php. Reused query from it.
  21. *
  22. * @return array The custom fields.
  23. */
  24. public static function get_custom_fields() {
  25. global $wpdb;
  26. // Use cached value if available.
  27. if ( ! is_null( self::$custom_fields ) ) {
  28. return self::$custom_fields;
  29. }
  30. self::$custom_fields = [];
  31. /**
  32. * Filters the number of custom fields to retrieve for the drop-down
  33. * in the Custom Fields meta box.
  34. *
  35. * @param int $limit Number of custom fields to retrieve. Default 30.
  36. */
  37. $limit = apply_filters( 'postmeta_form_limit', 30 );
  38. $sql = "SELECT DISTINCT meta_key
  39. FROM $wpdb->postmeta
  40. WHERE meta_key NOT BETWEEN '_' AND '_z'
  41. HAVING meta_key NOT LIKE %s
  42. ORDER BY meta_key
  43. LIMIT %d";
  44. $fields = $wpdb->get_col( $wpdb->prepare( $sql, $wpdb->esc_like( '_' ) . '%', $limit ) );
  45. if ( is_array( $fields ) ) {
  46. self::$custom_fields = array_map( [ 'WPSEO_Custom_Fields', 'add_custom_field_prefix' ], $fields );
  47. }
  48. return self::$custom_fields;
  49. }
  50. /**
  51. * Adds the cf_ prefix to a field.
  52. *
  53. * @param string $field The field to prefix.
  54. *
  55. * @return string The prefixed field.
  56. */
  57. private static function add_custom_field_prefix( $field ) {
  58. return 'cf_' . $field;
  59. }
  60. }