Как получить информацию из метабокса в WordPress и показать ее в шаблоне страницы - PullRequest
0 голосов
/ 14 октября 2019

У меня проблемы с отображением метаданных метабокса на странице шаблона. Похоже, что данные сохранены. Где я ошибаюсь при отображении данных на странице?

Привет, который я поставил внутри проверки, если переменная установлена, отображается на странице, но не отображаетсясами переменные. Я пробовал разные места для сохранения информации в файле functions.php, но место, которое я указал, кажется, единственное место, в котором информация сохраняется в них. Там что-то не так? или как я пытаюсь отобразить их на странице?

Это со стороны моего шаблона, HTML-код. (page-средства.php)

<aside class="facility-content-sidebar">
  <?php
      if ( isset( $mf ) && '' !== $mf ) {
        echo 'hello';
        echo esc_attr( $mf );
     }
     if ( isset( $ls ) && '' !== $ls ) {
        echo 'hello';
        echo esc_attr( $ls );
     }
  ?>
</aside>

Это весь мой код для этого в functions.php

/* Opening Hours meta box on template */
add_action('add_meta_boxes', 'add_openinghours_meta');
function add_openinghours_meta() {
    global $post;

    if(!empty($post))
    {
        $pageTemplate = get_post_meta($post->ID, '_wp_page_template', true);

        if($pageTemplate == 'page-facility.php' )
        {
            add_meta_box(
                'openinghours_meta', // $id
                'Öppettider', // $title
                'display_opening_information', // $callback
                'page', // $page
                'normal', // $context
                'high'); // $priority
        }
    }
}

if ( ! function_exists( 'display_opening_information' ) ) {

    /**
     * Meta box render function
     *
     * @param  object $post Post object.
     * @since  1.0.0
     */

    function display_opening_information($post) {
        // Add the HTML for the post meta
        $meta = get_post_meta( $post->ID );
        $openinghours_mf_input_field = ( isset( $meta['openinghours_mf_input_field'][0] ) && '' !== $meta['openinghours_mf_input_field'][0] ) ? $meta['openinghours_mf_input_field'][0] : '';
        $openinghours_ls_input_field = ( isset( $meta['openinghours_ls_input_field'][0] ) && '' !== $meta['openinghours_ls_input_field'][0] ) ? $meta['openinghours_ls_input_field'][0] : '';
        wp_nonce_field( 'openinghours_control_meta_box', 'openinghours_control_meta_box_nonce' ); // Always add nonce to your meta boxes!
        ?>
        <div class="post_meta_extras">
            <p>
                <label><?php esc_attr_e( 'Måndag-Fredag:', 'openinghours_mf_input_field' ); ?></label>
                <input type="text" name="openinghours_mf_input_field" value="<?php echo esc_attr( $openinghours_mf_input_field ); ?>">
            </p>
            <p>
                <label><?php esc_attr_e( 'Lördag-Söndag:', 'openinghours_ls_input_field' ); ?></label>
                <input type="text" name="openinghours_ls_input_field" value="<?php echo esc_attr( $openinghours_ls_input_field ); ?>">
            </p>
        </div>
        <?php
    }
}

add_action( 'save_post', 'openinghours_save_metabox' );

if ( ! function_exists( 'openinghours_save_metabox' ) ) {
    /**
     * Save controls from the meta boxes
     *
     * @param  int $post_id Current post id.
     * @since 1.0.0
     */
    function openinghours_save_metabox( $post_id ) {
        /*
         * We need to verify this came from the our screen and with proper authorization,
         * because save_post can be triggered at other times. Add as many nonces, as you
         * have metaboxes.
         */
        if ( ! isset( $_POST['openinghours_control_meta_box_nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['openinghours_control_meta_box_nonce'] ), 'openinghours_control_meta_box' ) ) { // Input var okay.
            return $post_id;
        }

        // Check the user's permissions.
        if ( isset( $_POST['post_type'] ) && 'page' === $_POST['post_type'] ) { // Input var okay.
            if ( ! current_user_can( 'edit_page', $post_id ) ) {
                return $post_id;
            }
        } else {
            if ( ! current_user_can( 'edit_post', $post_id ) ) {
                return $post_id;
            }
        }

        /*
         * If this is an autosave, our form has not been submitted,
         * so we don't want to do anything.
         */
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return $post_id;
        }

        /* Ok to save */

        if ( isset( $_POST['openinghours_mf_input_field'] ) ) { // Input var okay.
            update_post_meta( $post_id, 'openinghours_mf_input_field', sanitize_text_field( wp_unslash( $_POST['openinghours_mf_input_field'] ) ) ); // Input var okay.
        }
        if ( isset( $_POST['openinghours_ls_input_field'] ) ) { // Input var okay.
            update_post_meta( $post_id, 'openinghours_ls_input_field', sanitize_text_field( wp_unslash( $_POST['openinghours_ls_input_field'] ) ) ); // Input var okay.
        }

    }

    $mf = get_post_meta( get_the_ID(), 'openinghours_mf_input_field', true );
    $ls = get_post_meta( get_the_ID(), 'openinghours_ls_input_field', true );
}

Я хочу, чтобы переменные печатались с информацией, которая помещается вметабокс. Чтобы показать часы работы объекта.

Ответы [ 2 ]

0 голосов
/ 16 октября 2019

Я поместил код;

$mf = get_post_meta( get_the_ID(), 'openinghours_mf_input_field', true );
$ls = get_post_meta( get_the_ID(), 'openinghours_ls_input_field', true );

внутри функции, он должен был быть в цикле WordPress, я, наконец, понял это прошлой ночью, просто забыл опубликовать его здесь. Спасибо всем за внимание к моей проблеме!

Так вот вместо этого;

<aside class="facility-content-sidebar">
  <?php
      $mf = get_post_meta( get_the_ID(), 'openinghours_mf_input_field', true );
      $ls = get_post_meta( get_the_ID(), 'openinghours_ls_input_field', true );

      if ( isset( $mf ) && '' !== $mf ) {
        echo 'hello';
        echo esc_attr( $mf );
     }
     if ( isset( $ls ) && '' !== $ls ) {
        echo 'hello';
        echo esc_attr( $ls );
     }
  ?>
</aside>
0 голосов
/ 15 октября 2019

Убедитесь, что переменные $mf и $ls инициализированы в файле шаблона page-facility.php.

Например:

<aside class="facility-content-sidebar">
  <?php
     //initilize variables
     $mf = get_post_meta( get_the_ID(), 'openinghours_mf_input_field', true );
     $ls = get_post_meta( get_the_ID(), 'openinghours_ls_input_field', true );

     //then check if empty
     if ( isset( $mf ) && '' !== $mf ) {
        echo 'hello';
        echo esc_attr( $mf );
     }
     if ( isset( $ls ) && '' !== $ls ) {
        echo 'hello';
        echo esc_attr( $ls );
     }
  ?>
</aside>
...