Wordpress CPT добавляет новые перезаписывает существующие - PullRequest
0 голосов
/ 16 апреля 2020

Я работаю над проектом Wordpress и добавил несколько пользовательских типов сообщений и метабоксов. Внутри моей виртуальной машины все работает нормально, но на сервере второй CPT, который я добавляю, перезаписывает предыдущий. Это происходит только для магазинов CPT, другие, которые я добавил, работают так, как должны.

Я поместил код для CPT и метабоксов в разные файлы и включил их в свои функции. php для каждого CPT.

Вот файл custom-post-type-shop. php для магазина

<?php

/**
 * Plugin Name: BUYeinander Shops
 * Version: 0.1
 * Text Domain: buy_shops
 **/

// Register Shop Custom Post Type
function buy_shops()
{
    $labels = array(
        'name' => _x('Shops', 'Post Type General Name', 'buy_shops'),
        'singular_name' => _x('Shop', 'Post Type Singular Name', 'buy_shops'),
        'menu_name' => __('Shops', 'buy_shops'),
        'name_admin_bar' => __('Shops', 'buy_shops'),
        'archives' => __('Shop Archives', 'buy_shops'),
        'attributes' => __('Shop Attributes', 'buy_shops'),
        'parent_item_colon' => __('Parent Shop:', 'buy_shops'),
        'all_items' => __('All Shops', 'buy_shops'),
        'add_new_item' => __('Add New Shop', 'buy_shops'),
        'add_new' => __('Add New', 'buy_shops'),
        'new_item' => __('New Shop', 'buy_shops'),
        'edit_item' => __('Edit Shop', 'buy_shops'),
        'update_item' => __('Update Shop', 'buy_shops'),
        'view_item' => __('View Shop', 'buy_shops'),
        'view_items' => __('View Shops', 'buy_shops'),
        'search_items' => __('Search Shop', 'buy_shops'),
        'not_found' => __('Not found', 'buy_shops'),
        'not_found_in_trash' => __('Not found in Trash', 'buy_shops'),
        'featured_image' => __('Shop Image', 'buy_shops'),
        'set_featured_image' => __('Set Shop image', 'buy_shops'),
        'remove_featured_image' => __('Remove Shop image', 'buy_shops'),
        'use_featured_image' => __('Use as Shop image', 'buy_shops'),
        'insert_into_item' => __('Insert into Shop', 'buy_shops'),
        'uploaded_to_this_item' => __('Uploaded to this Shop', 'buy_shops'),
        'items_list' => __('Shops list', 'buy_shops'),
        'items_list_navigation' => __('Shops list navigation', 'buy_shops'),
        'filter_items_list' => __('Filter Shops list', 'buy_shops'),
    );

    $args = array(
    'label' => __('Shops', 'buy_shops'),
    'description' => __('Shop-Eintrag', 'buy_shops'),
    'labels' => $labels,
    'supports' => array(
            'title',
            // 'editor',
            // 'thumbnail',
            // 'comments',
            'revisions',
            // 'custom-fields'
        ),
        // 'taxonomies' => array( 'category' ),
        'hierarchical' => true,
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_position' => 20,
        'menu_icon' => 'dashicons-store',
        'show_in_admin_bar' => true,
        'show_in_nav_menus' => true,
        'can_export' => true,
        'has_archive' => true,
        'exclude_from_search' => false,
        'publicly_queryable' => true,
        'capability_type' => 'page',
        'show_in_rest' => true,
      );

    register_post_type('Shops', $args);
}
add_action('init', 'buy_shops', 0);

Это файл meta -box-shop. php для метабокса

<?php

// Metabox for shops
$prefix_shop = 'buy_shop_';

$regionargs = array(
    'post_type' => "regionen",
    'post_status' => 'publish'
);

$regionquery = new WP_Query($regionargs);
$regions = [];

if ($regionquery->have_posts()) {
    while ($regionquery->have_posts()) {
        $regionquery->the_post();
        $regionTitle = $regionquery->post->post_title;

        if (!in_array($regionTitle, $regions)) {
            $regions[] = $regionTitle;
        }
    }
}

$shop_meta_box = array(
    'id' => 'shop-meta-box',
    'title' => 'Shop Informationen',
    'page' => 'Shops',
    'context' => 'normal',
    'priority' => 'high',
    'fields' => array(
        array(
            'name' => 'Untertitel',
            'desc' => '',
            'id' => $prefix_shop . 'description',
            'type' => 'text',
            'std' => ''
        ),
        array(
            'name' => 'Straße',
            'desc' => '',
            'id' => $prefix_shop . 'street',
            'type' => 'text',
            'std' => ''
        ),
        array(
            'name' => 'Hausnummer',
            'desc' => '',
            'id' => $prefix_shop . 'housenumber',
            'type' => 'number',
            'std' => ''
        ),
        array(
            'name' => 'Postleitzahl',
            'desc' => '',
            'id' => $prefix_shop . 'zipcode',
            'type' => 'number',
            'std' => ''
        ),
        array(
            'name' => 'Stadt',
            'desc' => '',
            'id' => $prefix_shop . 'city',
            'type' => 'text',
            'std' => ''
        ),
        array(
            'name' => 'Internetadresse',
            'desc' => '',
            'id' => $prefix_shop . 'url',
            'type' => 'text',
            'std' => ''
        ),
        array(
            'name' => 'Region',
            'desc' => '',
            'id' => $prefix_shop . 'region',
            'type' => 'select',
            'std' => '',
            'options' => $regions
        ),
        array(
            'name' => 'Zweigstelle',
            'desc' => '',
            'id' => $prefix_shop . 'branch',
            'type' => 'checkbox',
            'std' => ''
        ),
    )
);

add_action('admin_menu', 'shop_add_box');

// Add meta box
function shop_add_box()
{
    global $shop_meta_box;

    add_meta_box($shop_meta_box['id'], $shop_meta_box['title'], 'shop_show_box', $shop_meta_box['page'], $shop_meta_box['context'], $shop_meta_box['priority']);
}


// Callback function to show fields in meta box
function shop_show_box()
{
    global $shop_meta_box, $post;

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

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

    foreach ($shop_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['desc'];
            break;
            case 'number':
                echo '<input type="number" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:50%" />', '<br />', $field['desc'];
            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['desc'];
            //     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;
            }

        echo     '</td><td>',
        '</td></tr>';
    }

    echo '</table>';
}

add_action('save_post', 'shop_save_data');

// Save data from meta box
function shop_save_data($post_id)
{
    global $shop_meta_box;

    // verify nonce
    if (!wp_verify_nonce($_POST['shop_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 ($shop_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);
        }
    }
}

/*
 * Add a meta box for image upload
 */


function lacuna2_case_study_bg( $post ) {
    wp_nonce_field( 'case_study_bg_submit', 'case_study_bg_nonce' );
    $lacuna2_stored_meta = get_post_meta( $post->ID ); ?>

    <p>
        <img style="max-width:200px;height:auto;" id="meta-image-preview" src="<?php if ( isset ( $lacuna2_stored_meta['meta-image'] ) ){ echo $lacuna2_stored_meta['meta-image'][0]; } ?>" /> <br>
        <input type="text" name="meta-image" id="meta-image" class="meta_image" value="<?php if ( isset ( $lacuna2_stored_meta['meta-image'] ) ){ echo $lacuna2_stored_meta['meta-image'][0]; } ?>" />
        <input type="button" id="meta-image-button" class="button" value="Choose or Upload an Image" />
    </p>
<script>
jQuery('#meta-image-button').click(function() {

    var send_attachment_bkp = wp.media.editor.send.attachment;

    wp.media.editor.send.attachment = function(props, attachment) {

        jQuery('#meta-image').val(attachment.url);
    jQuery('#meta-image-preview').attr('src',attachment.url);
        wp.media.editor.send.attachment = send_attachment_bkp;
    }

    wp.media.editor.open();

    return false;
});
</script>
<?php    

}

/**
 * Add Case Study background image metabox to the back end of Case Study posts
 */

function lacuna2_add_meta_boxes() {
    add_meta_box( 'case-study-bg', 'Shop Bilddatei', 'lacuna2_case_study_bg', 'shops', 'normal', 'high' );
}
add_action( 'add_meta_boxes', 'lacuna2_add_meta_boxes' );

/**
 * Save background image metabox for Case Study posts
 */

function save_case_study_bg_meta_box( $post_id ) {
    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );
    $is_valid_nonce = ( isset( $_POST[ 'case_study_bg_nonce' ] ) && wp_verify_nonce( $_POST[ 'case_study_bg_nonce' ], 'case_study_bg_submit' ) ) ? 'true' : 'false';

    // Exits script depending on save status
    if ( $is_autosave || $is_revision || !$is_valid_nonce  ) {
        return;
    }

    // Checks for input and sanitizes/saves if needed
    if( isset( $_POST[ 'meta-image' ] ) ) {
        update_post_meta( $post_id, 'meta-image', $_POST[ 'meta-image' ] );
    }
}

add_action( 'save_post', 'save_case_study_bg_meta_box' );

1 Ответ

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

1) Убедитесь, что оба post_types используют уникальный ключ post_type. Это первый параметр для функции register_post_type. См. Документы: https://developer.wordpress.org/

2) Также: обязательно используйте ключ post_type только с символами нижнего регистра. Как я могу процитировать документацию:

$ post_type (строка) (обязательно) Ключ типа сообщения. Не должен превышать 20 символов и может содержать только строчные буквы alphanumeri c символы, тире и подчеркивания.

Так что измените:

register_post_type('Shops', $args);

в:

register_post_type('shops', $args);

...