Wordpress Documentation

advertise, Anuncio

APIS WP_Query, WP_User_Query, WP_Term_Query, Transients, Almacena datos en caché de forma temporal, mucho más

📚 WP_Query (Entradas/CPTs)

				
					$query = new WP_Query([
  'post_type' => 'book',
  'posts_per_page' => 5,
  'meta_query' => [
    [
      'key' => '_book_genre',
      'value' => 'Fantasía',
      'compare' => 'LIKE'
    ]
  ]
]);

while ($query->have_posts()) {
  $query->the_post();
  echo '<h2>' . get_the_title() . '</h2>';
}
wp_reset_postdata();

				
			

👥 WP_User_Query

				
					$user_query = new WP_User_Query([
  'role' => 'author',
  'meta_key' => 'especialidad',
  'meta_value' => 'nutrición'
]);

foreach ($user_query->get_results() as $user) {
  echo $user->display_name;
}

				
			

🏷️ WP_Term_Query

				
					$terms = get_terms([
  'taxonomy' => 'category',
  'hide_empty' => false,
]);

foreach ($terms as $term) {
  echo $term->name;
}

				
			

Transients API

Almacena datos en caché de forma temporal.

				
					$data = get_transient('mis_datos');

if (!$data) {
  $data = wp_remote_get('https://api.example.com/data');
  set_transient('mis_datos', $data, 60 * 5); // 5 minutos
}

print_r($data);

				
			

⚙️ 4. Options API

Guardar y obtener configuraciones globales.

				
					// Guardar opción
update_option('mi_plugin_api_key', '123456');

// Obtener opción
$clave = get_option('mi_plugin_api_key');

				
			

🛠️ 5. Settings API

Panel de configuración en WP Admin.

				
					// En functions.php o plugin
add_action('admin_init', function () {
  register_setting('mis-ajustes', 'mi_texto');
  add_settings_section('seccion1', 'Ajustes Personalizados', null, 'general');
  add_settings_field('campo1', 'Texto:', function () {
    $valor = get_option('mi_texto');
    echo '<input type="text" name="mi_texto" value="' . esc_attr($valor) . '">';
  }, 'general', 'seccion1');
});

				
			

🧩 6. Shortcodes API

Ejemplo para crear [saludo]

				
					add_shortcode('saludo', function ($atts) {
  $atts = shortcode_atts(['nombre' => 'Erick'], $atts);
  return "Hola, {$atts['nombre']}";
});

				
			

📦 7. Widgets API (legacy)

🧱 Widget moderno (bloques) requiere JS/React → Gutenberg Block API

				
					class Mi_Widget extends WP_Widget {
  function __construct() {
    parent::__construct('mi_widget', 'Mi Widget');
  }

  function widget($args, $instance) {
    echo $args['before_widget'];
    echo '<p>Hola desde widget</p>';
    echo $args['after_widget'];
  }
}

add_action('widgets_init', function () {
  register_widget('Mi_Widget');
});

				
			

🌐 8. REST API

				
					add_action('rest_api_init', function () {
  register_rest_route('miapi/v1', '/libros/', [
    'methods' => 'GET',
    'callback' => 'obtener_libros',
  ]);
});

function obtener_libros() {
  $query = new WP_Query(['post_type' => 'book', 'posts_per_page' => 5]);
  $result = [];

  foreach ($query->posts as $post) {
    $result[] = [
      'titulo' => get_the_title($post),
      'autor' => get_post_meta($post->ID, '_book_author', true),
    ];
  }

  return rest_ensure_response($result);
}

				
			

🌍 9. HTTP API (API externa)

				
					$response = wp_remote_get('https://jsonplaceholder.typicode.com/posts');
if (!is_wp_error($response)) {
  $data = json_decode(wp_remote_retrieve_body($response), true);
  print_r($data);
}

				
			
				
					$response = wp_remote_post('https://api.example.com/send', [
  'body' => [
    'nombre' => 'Erick',
    'email' => 'ejemplo@email.com'
  ]
]);

				
			

🕑 10. Cron API

⚠️ Tip: WordPress cron depende del tráfico (no es un cron real del servidor).

				
					add_action('mi_evento_programado', 'mi_funcion_programada');

function mi_funcion_programada() {
  error_log('Tarea ejecutada');
}

if (!wp_next_scheduled('mi_evento_programado')) {
  wp_schedule_event(time(), 'hourly', 'mi_evento_programado');
}

				
			

🔀 11. Rewrite API

URL amigables personalizadas:

				
					add_action('init', function () {
  add_rewrite_rule('libro/([0-9]+)/?', 'index.php?book_id=$matches[1]', 'top');
  add_rewrite_tag('%book_id%', '([0-9]+)');
});

				
			

Y en template:

				
					$id = get_query_var('book_id');

				
			

🔁 Recuerda ejecutar flush_rewrite_rules() una vez al activar el plugin.