WordPress - Загрузка изображений в пользовательском типе сообщения очищается при обновлении

Я пытаюсь создать базовый плагин для внутреннего использования, используя пользовательский тип записи. Я не хочу использовать ACF (настолько, насколько мне это нравится), поскольку мне нужно позволить другим в моем учреждении установить и настроить его на нескольких сайтах, и мне нужно, чтобы он был максимально простым для них.

Я только начинаю, но сталкиваюсь с проблемой с Image Uploader. Я искал и попробовал полдюжины примеров здесь и на других сайтах, но я все еще застрял. Любая помощь будет принята с благодарностью.

Проблема в том, что я могу получить изображение для загрузки или выбрать его из медиа-библиотеки. Он появляется в интерфейсе администратора, когда я выбираю его. Но как только я нажимаю "Опубликовать" или "Обновить", изображение исчезает, и значение URL, установленное этим изображением, само очищается.

Однако значение URL отображается в самой базе данных. Таким образом, он загружается и изменяется, но когда страница перезагружается, он говорит, что значение пусто.

Вот мой php-файл, за исключением информации заголовка, настройки пользовательского типа записи, таксономий и мета-блоков. Это метабокс "Отображать изображения" (многое из этого бесполезно для проблемы, пожалуйста, дайте мне знать, если мне нужно немного его отредактировать)

<?php
//Enqueues
if(is_admin()) {
    wp_enqueue_script('directory-js', plugins_url('/umkc-directory/js/directory.js'));
    wp_enqueue_style('som-directory', plugins_url('/umkc-directory/css/som-directory.css'));
}

//create the Custom Post Type
add_action( 'init', 'create_umkc_directory' );

function create_umkc_directory() {
    register_post_type( 'directory',
    array(
        'labels' => array(
            'name' => 'Directory',
            'singular_name' => 'Directory Entry',
            'add_new' => 'Add New',
            'add_new_item' => 'Add Directory Entry',
            'edit' => 'Edit',
            'edit_item' => 'Edit Directory Entry',
            'new_item' => 'New Directory Entry',
            'view' => 'View',
            'view_item' => 'View Directory Entry',
            'search_items' => 'Search Directory Entries',
            'not_found' => 'No Directory Entries found',
            'not_found_in_trash' => 'No Directory Entries found in Trash',
            'parent' => 'Parent Directory Entry'
        ),

        'public' => true,
        'menu_position' => 20,
        'supports' => array( 'title' ),
        'taxonomies' => array( 'department', 'area' ),
        'menu_icon' => plugins_url( 'images/icon.png', __FILE__ ),
        'has_archive' => true
    )
);
}

//Register taxonomies
add_action( 'init', 'create_directory_tax' );

function create_directory_tax() {
register_taxonomy(
    'department',
    'directory',
    array(
        'label' => __( 'Department' ),
        'rewrite' => array( 'slug' => 'department' ),
        'hierarchical' => false,
        'update_count_callback' => '_update_post_term_count',
    )
);
register_taxonomy(
    'area',
    'directory',
    array(
        'label' => __( 'Specialty and Research Areas' ),
        'rewrite' => array( 'slug' => 'area' ),
        'hierarchical' => false,
        'update_count_callback' => '_update_post_term_count',
    )
);
}

//Add meta boxes to Admin interface
add_action( 'admin_init', 'my_admin' );

function my_admin() {
add_meta_box( 'directory_vitals_meta_box',
    'Vitals',
    'display_directory_vitals_meta_box',
    'directory', 'normal', 'high'
);
add_meta_box( 'directory_photos_meta_box',
     'Photos',
     'display_directory_photos_meta_box',
     'directory', 'normal', 'high'
);
add_meta_box( 'directory_contact_meta_box',
    'Contact Information',
    'display_directory_contact_meta_box',
    'directory', 'normal', 'core'
);
add_meta_box( 'directory_background_meta_box',
    'Education and Background',
    'display_directory_background_meta_box',
    'directory', 'normal', 'low'
);
add_meta_box( 'directory_specialty_meta_box',
    'Specialty and Research Information',
    'display_directory_specialty_meta_box',
    'directory', 'normal', 'low'
);
add_meta_box( 'directory_pubs_meta_box',
    'Publications and Media',
    'display_directory_pubs_meta_box',
    'directory', 'normal', 'low'
);
}


//Vitals Meta box
function display_directory_vitals_meta_box( $directory_entry ) {
// Retrieve fields based on entry ID
echo '<input type="hidden" name="diretory_contact_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
$directory_fname = esc_html( get_post_meta( $directory_entry->ID, 'directory_fname', true ) );
$directory_midname = esc_html( get_post_meta( $directory_entry->ID, 'directory_midname', true ) );
$directory_lname = esc_html( get_post_meta( $directory_entry->ID, 'directory_lname', true ) );
$directory_suffix = esc_html( get_post_meta( $directory_entry->ID, 'directory_suffix', true ) );
$directory_affiliate = esc_html( get_post_meta( $directory_entry->ID, 'directory_affiliate', true ) );
$directory_dept = esc_html( get_post_meta( $directory_entry->ID, 'directory_dept', true ) );
$directory_section = esc_html( get_post_meta( $directory_entry->ID, 'directory_section', true ) );
$directory_facultyappt = esc_html( get_post_meta( $directory_entry->ID, 'directory_facultyappt', true ) );
$directory_adminappt = esc_html( get_post_meta( $directory_entry->ID, 'directory_adminappt', true ) );
$directory_addtitle1 = esc_html( get_post_meta( $directory_entry->ID, 'directory_addtitle1', true ) );
$directory_addtitle2 = esc_html( get_post_meta( $directory_entry->ID, 'directory_addtitle2', true ) );
$directory_addtitle3 = esc_html( get_post_meta( $directory_entry->ID, 'directory_addtitle3', true ) );
?>
<table width="100%" class="diradmin">
    <tr>
      <td width="8.5%"></td>
      <td width="8.5%"></td>
      <td width="8.5%"></td>
      <td width="8.5%"></td>
      <td width="8.5%"></td>
      <td width="8.5%"></td>
      <td width="8.5%"></td>
      <td width="8.5%"></td>
      <td width="8.5%"></td>
      <td width="8.5%"></td>
      <td width="8.5%"></td>
      <td width="8.5%"></td>
    </tr>
    <tr>
      <td colspan="4"><lable>First Name</lable><br><input type="text" name="directory_fname" value="<?php echo $directory_fname; ?>" /></td>
      <td colspan="2"><lable>Middle Name/Initial</lable><br><input type="text" name="directory_midname" value="<?php echo $directory_midname; ?>" /></td>
      <td colspan="4"><lable>Last Name</lable><br><input type="text" name="directory_lname" value="<?php echo $directory_lname; ?>" /></td>
      <td colspan="2"><lable>Suffix</lable><br><input type="text" name="directory_suffix" value="<?php echo $directory_suffix; ?>" /></td>
    </tr>
    <tr>
      <td colspan="4"><lable>Primary Hospital Affiliate</lable><br><input type="text" name="directory_affiliate" value="<?php echo $directory_affiliate; ?>" /></td>
      <td colspan="4"><lable>Department</lable><br><input type="text" name="directory_dept" value="<?php echo $directory_dept; ?>" /></td>
      <td colspan="4"><lable>Section</lable><br><input type="text" name="directory_section" value="<?php echo $directory_section; ?>" /></td>
    </tr>
    <tr>
      <td colspan="6"><lable>Faculty Appointment</lable><br><input type="text" name="directory_facultyappt" value="<?php echo $directory_facultyappt; ?>" /></td>
      <td colspan="6"><lable>Administrative Appointment</lable><br><input type="text" name="directory_adminappt" value="<?php echo $directory_adminappt; ?>" /></td>
    </tr>
    <tr>
      <td colspan="4"><lable>Additional Title</lable><br><input type="text" name="directory_addtitle1" value="<?php echo $directory_addtitle1; ?>" /></td>
      <td colspan="4"><lable>Additional Title</lable><br><input type="text" name="directory_addtitle2" value="<?php echo $directory_addtitle2; ?>" /></td>
      <td colspan="4"><lable>Additional Title</lable><br><input type="text" name="directory_addtitle3" value="<?php echo $directory_addtitle3; ?>" /></td>
    </tr>
</table>
<?php
}

//Display the Images meta box
function display_directory_photos_meta_box() {
    ?>
    <input type="hidden" name="directory_portrait" />
    <?php $portrait_img = get_post_meta($directory_entry->ID,'directory_portrait',true); ?>
    <input id="upload_image_button" type="button" value="<?php echo (empty($portrait_img)?'Upload Portrait':'Change Portrait') ?>" />
    <div id="show_directory_portrait"><?php echo (!empty($portrait_img)?"<img src='$portrait_img' width='220' />":'')?></div>
<?php 
}

//Contact Meta box
function display_directory_contact_meta_box( $directory_entry ) {
// Retrieve fields based on entry ID
$directory_location = esc_html( get_post_meta( $directory_entry->ID, 'directory_location', true ) );
$directory_email = esc_html( get_post_meta( $directory_entry->ID, 'directory_email', true ) );
$directory_phone = esc_html( get_post_meta( $directory_entry->ID, 'directory_phone', true ) );
?>
<table>
    <tr>
        <td style="width: 30%">Location/Office</td>
        <td style="width: 40%">Email</td>
        <td style="width: 30%">Phone</td>
    </tr>
    <tr>
        <td><input type="text" size="30" name="directory_location" value="<?php echo $directory_location; ?>" /></td>
        <td><input type="text" size="42" name="directory_email" value="<?php echo $directory_email; ?>" /></td>
        <td><input type="text" size="40" name="directory_phone" value="<?php echo $directory_phone; ?>" /></td>
    </tr>
</table>
<?php
}   

//Save function
add_action( 'save_post', 'add_directory_entry_fields', 10, 2 );

function add_directory_entry_fields( $directory_entry_id, $directory_entry ) {
// Check post type for Directory Entries
if ( $directory_entry->post_type == 'directory' ) {
    // Store data in post meta table if present in post data
    if ( isset( $_POST['directory_fname'] ) && $_POST['directory_fname'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_fname', $_POST['directory_fname'] );
    }
    if ( isset( $_POST['directory_midname'] ) && $_POST['directory_midname'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_midname', $_POST['directory_midname'] );
    }
    if ( isset( $_POST['directory_lname'] ) && $_POST['directory_lname'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_lname', $_POST['directory_lname'] );
    }
    if ( isset( $_POST['directory_suffix'] ) && $_POST['directory_suffix'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_suffix', $_POST['directory_suffix'] );
    }
    if ( isset( $_POST['directory_affiliate'] ) && $_POST['directory_affiliate'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_affiliate', $_POST['directory_affiliate'] );
    }
    if ( isset( $_POST['directory_dept'] ) && $_POST['directory_dept'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_dept', $_POST['directory_dept'] );
    }
    if ( isset( $_POST['directory_section'] ) && $_POST['directory_section'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_section', $_POST['directory_section'] );
    }
    if ( isset( $_POST['directory_facultyappt'] ) && $_POST['directory_facultyappt'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_facultyappt', $_POST['directory_facultyappt'] );
    }
    if ( isset( $_POST['directory_adminappt'] ) && $_POST['directory_adminappt'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_adminappt', $_POST['directory_adminappt'] );
    }
    if ( isset( $_POST['directory_addtitle1'] ) && $_POST['directory_addtitle1'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_addtitle1', $_POST['directory_addtitle1'] );
    }
    if ( isset( $_POST['directory_addtitle2'] ) && $_POST['directory_addtitle2'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_addtitle2', $_POST['directory_addtitle2'] );
    }
    if ( isset( $_POST['directory_addtitle3'] ) && $_POST['directory_addtitle3'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_addtitle3', $_POST['directory_addtitle3'] );
    }
    if ( isset( $_POST['directory_location'] ) && $_POST['directory_location'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_location', $_POST['directory_location'] );
    }
    if ( isset( $_POST['directory_email'] ) && $_POST['directory_email'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_email', $_POST['directory_email'] );
    }
    if ( isset( $_POST['directory_phone'] ) && $_POST['directory_phone'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_phone', $_POST['directory_phone'] );
    }
    if ( isset( $_POST['directory_portrait'] ) && $_POST['directory_portrait'] != '' ) {
        update_post_meta( $directory_entry_id, 'directory_portrait', $_POST['directory_portrait'] );
    }
}
}

//Add Taxonomies as Columns in All Entries View
add_filter( 'manage_edit-directory_columns', 'my_columns' );

function my_columns( $columns ) {
$columns['department'] = 'Department';
$columns['area'] = 'Specialty and Research Areas';
return $columns;
}

add_action( 'manage_posts_custom_column', 'populate_columns' );

function populate_columns( $column ) {
if ( 'department' == $column ) {
    $department = esc_html( get_post_meta( get_the_ID(), 'department', true ) );
    echo $department;
}
elseif ( 'area' == $column ) {
    $area = get_post_meta( get_the_ID(), 'area', true );
    echo $area;
}
}

add_filter( 'manage_editdirectory_sortable_columns', 'sort_me' );

function sort_me( $columns ) {
$columns['department'] = 'department';
$columns['area'] = 'area';

return $columns;
}

add_filter( 'request', 'column_ordering' );

add_filter( 'request', 'column_orderby' );

function column_orderby ( $vars ) {
if ( !is_admin() )
    return $vars;
if ( isset( $vars['orderby'] ) && 'department' == $vars['orderby'] ) {
    $vars = array_merge( $vars, array( 'meta_key' => 'department', 'orderby' => 'meta_value' ) );
}
elseif ( isset( $vars['orderby'] ) && 'area' == $vars['orderby'] ) {
    $vars = array_merge( $vars, array( 'meta_key' => 'area', 'orderby' => 'meta_value' ) );
}
return $vars;
}

//Department Select dropdown
add_action( 'restrict_manage_posts', 'my_filter_list' );

function my_filter_list() {
$screen = get_current_screen();
global $wp_query;
if ( $screen->post_type == 'directory' ) {
    wp_dropdown_categories( array(
        'show_option_all' => 'Show All Departments',
        'taxonomy' => 'department',
        'name' => 'department',
        'orderby' => 'name',
        'selected' => ( isset( $wp_query->query['department'] ) ? $wp_query->query['department'] : '' ),
        'hierarchical' => false,
        'depth' => 3,
        'show_count' => false,
        'hide_empty' => false,
    ) );
}
}

add_filter( 'parse_query','perform_filtering' );

function perform_filtering( $query ) {
$qv = &$query->query_vars;
if ( ( $qv['department'] ) && is_numeric( $qv['department'] ) ) {
    $term = get_term_by( 'id', $qv['department'], 'department' );
    $qv['department'] = $term->slug;
}
}

?>

И javascript для кнопки загрузки, которая ставится в очередь, а не встроенная.

jQuery(document).ready(function() {

var orig_send_to_editor = window.send_to_editor;

jQuery('#upload_image_button').click(function() {
    formfield = jQuery(this).prev('input');
    tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true');

    window.send_to_editor = function(html) {
    var regex = /src="(.+?)"/;
    var rslt =html.match(regex);
    var imgurl = rslt[1];
    formfield.val(imgurl);
    tb_remove();
    jQuery('#show_'+formfield.attr('name')).html('<img src="'+imgurl+'" width="" />')

    window.send_to_editor = orig_send_to_editor;
}

return false;
});
});

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

0 ответов

Другие вопросы по тегам