Создание пользовательских сообщений в изображениях WordPress не работает - PullRequest
0 голосов
/ 01 апреля 2020

Я создал пользовательскую тему WordPress для клиента, и как часть этой темы я создал собственные сообщения, что означает, что они смогут добавлять повторяющиеся копии / слайды с изображениями на часть веб-сайта без необходимости приходить. мне. Большая часть этого взята из удивительного учебника по pluralsight, однако это единственный бит, который не работает.

Копия выглядит нормально, но у меня проблема с изображениями, не распознающими источник.

Мои функции. php код ...

---------  Custom Classes Post Type --------
*/

function create_post_type()
{
    register_post_type(
        'glasseye_classes',
        array(
            'labels' => array(
                'name' => __('Classes'),
                'singular_name' => __('Class')
            ),
            'public' => true,
            'has_archive' => true,
            'supports' => 'title'
        )
    );
}
add_action('init', 'create_post_type');

// define prefix 
$prefix = 'ge_';


$meta_box = array(

    'id' => 'classes-meta-box',
    'title' => 'Add New Class Listing',
    'page' => 'glasseye_classes',
    'context' => 'normal',
    'priority' => 'high',
    'fields' => array(
        array(
            'name' => 'Title',
            'descr' => 'Enter the copy for your phone',
            'id' => $prefix . 'phone_copy',
            'type' => 'text'
        ),
        array(
            'name' => 'Phone image URL',
            'descr' => 'Please paste the full URL for the phone gif. You can find this in the Media Libary',
            'id' => $prefix . 'phone_image',
            'type' => 'text',
        ),
        array(
            'name' => 'Box Theme',
            'descr' => 'This sets the color scheme for the class box.  Please look at Classes page to determine the appropriate theme for your new listing',
            'id' => $prefix . 'theme',
            'class' => $prefix . 'theme',
            'type' => 'theme_colors',
            'options' => array(
                array('color' => 'Pink'),
                array('color' => 'Purple'),
                array('color' => 'Teal'),
                array('color' => 'Green')
            )
        )

    ) //fields array


); // meta_box aray    

add_action('admin_menu', 'glasseye_add_box');

// Add meta box

function glasseye_add_box()
{
    global $meta_box;

    add_meta_box($meta_box['id'], $meta_box['title'], 'glasseye_show_box', $meta_box['page'], $meta_box['context'], $meta_box['priority']);
}


function glasseye_show_box()
{
    global $meta_box, $post;

    // Use nonce for verification
    echo '<input type="hidden" name="glasseye_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';

    echo '<table class="form-table">';

    foreach ($meta_box['fields'] as $field) {
        // get current post meta data
        $meta = get_post_meta($post->ID, $field['id'], true);

        echo '<tr>',
            '<th style="width:20%"><label for="',
            $field['id'],
            '">',
            $field['name'],
            '</label></th>',
            '<td>';
        switch ($field['type']) {
            case 'text':
                echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />', '<br />', $field['descr'];
                break;
            case 'textarea':
                echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>', '<br />', $field['descr'];
                break;
            case 'select':
                echo '<select name="', $field['id'], '" id="', $field['id'], '">';
                foreach ($field['options'] as $option) {
                    echo '<option ', $meta == $option ? ' selected="selected"' : '', '>', $option, '</option>';
                }
                echo '</select>';
                break;
            case 'radio':
                foreach ($field['options'] as $option) {
                    echo '<input type="radio" name="', $field['id'], '" value="', $option['value'], '"', $meta == $option['value'] ? ' checked="checked"' : '', ' />', $option['name'];
                }
                break;
            case 'checkbox':
                echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />';
                break;
            case 'theme_colors':
                echo $field['descr'], '<br><br>';
                foreach ($field['options'] as $option) {
                    echo '<label>', $option['color'], ' <input type="radio" name="', $field['id'], '" value="', $option['color'], '" id="', $field['id'] . '_' . strtolower($option['color']), '"class="', $field['class'], '"', $meta == $option['color'] ? ' checked="checked"' : '', ' /></label><br>';
                }
        }
        echo     '</td><td>',
            '</td></tr>';
    }

    echo '</table>';
}

add_action('save_post', 'glasseye_save_data');

// Save data from meta box
function glasseye_save_data($post_id)
{
    global $meta_box;

    // verify nonce
    if (!wp_verify_nonce($_POST['glasseye_meta_box_nonce'], basename(__FILE__))) {
        return $post_id;
    }

    // check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }

    // check permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id)) {
            return $post_id;
        }
    } elseif (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }

    foreach ($meta_box['fields'] as $field) {
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];

        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
    }
}

Где это указано в моем индексе. php ...

        <?php
        $args = array('post_type' => 'glasseye_classes', 'posts_per_page' => 10);
        $loop = new WP_Query($args);

        while ($loop->have_posts()) : $loop->the_post();
            the_content();

            $meta_box_fields = $meta_box['fields'];

            // returns the key for the Name field for each Class
            $phone_copy_key = $meta_box_fields[0]['id'];
            $phone_copy_value = get_post_meta($post->ID, $phone_copy_key, true);

            $image_key = $meta_box_fields[2]['id'];
            $image_value = get_post_meta($post->ID, $image, true);

            $class_skill_key = $meta_box_fields[3]['id'];
            $class_skill_value = get_post_meta($post->ID, $class_skill_key, true);

            $class_length_key = $meta_box_fields[4]['id'];
            $class_length_value = get_post_meta($post->ID, $class_length_key, true);

            $class_description_key = $meta_box_fields[5]['id'];
            $class_description_value = get_post_meta($post->ID, $class_description_key, true);

            $class_theme_key = $meta_box_fields[6]['id'];
            $class_theme_value = get_post_meta($post->ID, $class_theme_key, true);

        ?>


            <h1><?php echo $phone_copy_value ?></h1>
            <div class="phone-animation">
                <img class="phone-animation-xlarge phone-five-animation-xlarge" src="<?php bloginfo('template_url') ?>/images/circle.png" alt="red circle" />
                <img class="phone-animation-large phone-five-animation-large" src="<?php bloginfo('template_url') ?>/images/circle.png" alt="red circle" />
                <img class="phone-animation-medium phone-five-animation-medium" src="<?php bloginfo('template_url') ?>/images/circle.png" alt="red circle" />
                <img class="phone-animation-small phone-five-animation-small" src="<?php bloginfo('template_url') ?>/images/circle.png" alt="red circle" />
                <div class="phone-image-container">
                    <img src="<?php echo $phone_value ?>" class="instructor-headshot" alt="<?php echo $class_instructor_value ?> Headshot">

                </div>

            </div>
    </div>

как выглядит тег изображения в инструментах разработчика ...

<div class="phone-image-container">
                    <img src(unknown) class="instructor-headshot" alt=" Headshot">
   </div>

1 Ответ

0 голосов
/ 01 апреля 2020

Я пропустил определение phone_value (указано @Howard E), а также пропустил некоторые настройки с помощью image_key.

Обновлен код ...

     $phone_image_value = get_post_meta($post->ID, $phone_image_key, true);

Я также необходимо добавить несколько дополнительных битов, чтобы моя ленивая загрузка работала

<img data-src="<?php echo $phone_image_value ?>" class="lazy-load" alt="<?php echo $phone_copy_value ?>">

Работает, как и ожидалось.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...