Cómo hacer una API en WordPress

5 minutos de lectura

avatar de usuario
APSB

Esta es la primera vez que uso wordpress para crear aplicaciones. ahí quiero hacer una api pero no sé cómo hacerlo en wordpress.

este es mi código en el sitio web:

function drivers_post_type() {
    $labels = array(
        'name'                => _x( 'driver', 'Post Type General Name', 'text_domain' ),
        'singular_name'       => _x( 'driver', 'Post Type Singular Name', 'text_domain' ),
        'menu_name'           => __( 'driver', 'text_domain' ),
        'name_admin_bar'      => __( 'Post Type', 'text_domain' ),
        'parent_item_colon'   => __( 'Parent Item:', 'text_domain' ),
        'all_items'           => __( 'All Items', 'text_domain' ),
        'add_new_item'        => __( 'Add New Item', 'text_domain' ),
        'add_new'             => __( 'Add New', 'text_domain' ),
        'new_item'            => __( 'New Item', 'text_domain' ),
        'edit_item'           => __( 'Edit Item', 'text_domain' ),
        'update_item'         => __( 'Update Item', 'text_domain' ),
        'view_item'           => __( 'View Item', 'text_domain' ),
        'search_items'        => __( 'Search Item', 'text_domain' ),
        'not_found'           => __( 'Not found', 'text_domain' ),
        'not_found_in_trash'  => __( 'Not found in Trash', 'text_domain' ),
    );
    $args = array(
        'label'               => __( 'driver', 'text_domain' ),
        'description'         => __( 'driver', 'text_domain' ),
        'labels'              => $labels,
        'supports'            => array( 'title','thumbnail' ),
        'hierarchical'        => false,
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'menu_position'       => 5,
        'show_in_admin_bar'   => true,
        'show_in_nav_menus'   => true,
        'can_export'          => true,
        'has_archive'         => true,
        'exclude_from_search' => false,
        'publicly_queryable'  => true,
        'rewrite'             => array('slug' => 'driver'),
        'capability_type'     => 'page',
    );
    register_post_type( 'drivers', $args );
}
// Hook into the 'init' action
add_action( 'init', 'drivers_post_type', 0 );

// Little function to return a custom field value
function driverMB_get_custom_field( $value ) {
  global $post;

    $custom_field = get_post_meta( $post->ID, $value, true );
    if ( !empty( $custom_field ) )
      return is_array( $custom_field ) ? stripslashes_deep( $custom_field ) : stripslashes( wp_kses_decode_entities( $custom_field ) );

    return false;
}

// Register the Metabox
function driverMB_add_custom_meta_box() {
    add_meta_box( 
        'driverMB-meta-box', 
        __( 'driver Info', 'textdomain' ), 
        'driverMB_meta_box_output', 
        'drivers', 
        'normal', 
        'default' 
    );
}
add_action( 'add_meta_boxes', 'driverMB_add_custom_meta_box' );

// Output the Metabox
function driverMB_meta_box_output( $post ) {
  // create a nonce field
  wp_nonce_field( 'my_driverMB_meta_box_nonce', 'driverMB_meta_box_nonce' ); ?>

    <p>
        <label><b>ID</b></label>
        <label><?php echo get_the_ID() ?></label>
    </p>
    <p>
        <label><b>Username</b></label>
        <input type="text" placeholder="Username" name="username" id="username" value="<?php echo driverMB_get_custom_field( 'username' ); ?>" style="width:100%;" />
    </p>
    <p>
        <label><b>Password</b></label>
        <input type="password" placeholder="Password" name="password" id="password" value="<?php echo driverMB_get_custom_field( 'password' ); ?>" style="width:100%;" />
    </p>
    <p>
        <label><b>Email</b></label>
        <input type="text" placeholder="Email" name="email" id="email" value="<?php echo driverMB_get_custom_field( 'email' ); ?>" style="width:100%;" />
    </p>
    <p>
        <label><b>Phone Number</b></label>
        <input type="text" placeholder="Ext : 088216192560" name="phone" id="phone" value="<?php echo driverMB_get_custom_field( 'phone' ); ?>" style="width:100%;" />
    </p>

  <?php
}

// Save the Metabox values
function driverMB_meta_box_save( $post_id ) {
  // Stop the script when doing autosave
  if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

  // Verify the nonce. If insn't there, stop the script
  if( !isset( $_POST['driverMB_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['driverMB_meta_box_nonce'], 'my_driverMB_meta_box_nonce' ) ) return;

  // Stop the script if the user does not have edit permissions
  if( !current_user_can( 'edit_post' ) ) return;

    // Save the textfield
  if( isset( $_POST['username'] ) )
    update_post_meta( $post_id, 'username', esc_attr( $_POST['username'] ) );
  if( isset( $_POST['password'] ) )
    update_post_meta( $post_id, 'password', esc_attr( $_POST['password'] ) );
  if( isset( $_POST['email'] ) )
    update_post_meta( $post_id, 'email', esc_attr( $_POST['email'] ) );
  if( isset( $_POST['phone'] ) )
    update_post_meta( $post_id, 'phone', esc_attr( $_POST['phone'] ) );
}
add_action( 'save_post', 'driverMB_meta_box_save' );

no sé cómo crearlo como api. mi amigo me dijo que creara si la url es igual y luego realizara la función de acción, pero no sé cómo.

¿Alguien me dice o me ayuda a crear una api para wordpress?

avatar de usuario
Jenis Patel

Sin duda, también hay muchos otros complementos en el mercado, pero estos son los dos que usé personalmente para crear API en WordPress:

  1. Usando API de descanso de WP (Hoy en día es oficialmente compatible con WordPress): Se proporciona la documentación detallada para el mismo aquí.

  2. Usando API JSON complemento (por simplicidad). Si usa este complemento, le permitirá crear sus archivos de “Controlador”, “Modelo”, etc. y, por lo tanto, puede escribir sus puntos finales personalizados. Puedes consultar más detalles aquí.

Nota: he usado este complemento el año pasado y funciona muy bien.

  • Este complemento no ha sido probado con las últimas 3 versiones principales de WordPress. Es posible que ya no se mantenga o soporte y que tenga problemas de compatibilidad cuando se usa con versiones más recientes de WordPress.

    – Yohanim

    13 de diciembre de 2018 a las 7:55

Para responder a tu pregunta, debo decir:

Primero debe crear una carpeta en la ruta principal de WordPress y colocar los archivos de su proyecto en ella.
ingrese la descripción de la imagen aquí

Luego agregue su archivo original con extensión .php Póngalo en él. Tenga en cuenta que debe mover su código en función de la función.

¿Ha sido útil esta solución?