自定义帖子类型禁用标题时出现错误[列‘POST_TITLE’不能为空]

时间:2017-02-14 作者:Nate

我正在为前端滑块创建自定义帖子类型。它接受在自定义字段中输入的值,并将其用作文章标题。它在我的本地主机和个人主机上都能完美地工作。但是,当我在客户端的主机上安装它时,会出现以下错误:

Notice: Undefined index: wys_slider_title in /data02/client_id/public_html/wp-content/themes/waiyin2015/inc/cpt/slides.php on line 302
WordPress database error: [Column \'post_title\' cannot be null]
第302行是发布幻灯片标题的函数。完整功能如下:

function wys_slide_title( $data , $postarr ) {
    if( $data[\'post_type\'] == \'slider\' ) {
        $slide_title = $_POST[\'wys_slider_title\']; // <<<<<< This is line 302
        $new_title = $slide_title;
        // Set slug date
        $post_date = date(\'Ymd-His\');
        // $post_slug = sanitize_title_with_dashes($post_date, \'\', $context = \'save\');
        $post_slugsan = sanitize_title($post_date);
        $data[\'post_title\'] = $new_title;
        $data[\'post_name\'] = $post_slugsan;  
    }
    return $data;
}
add_filter( \'wp_insert_post_data\' , \'wys_slide_title\' , \'99\', 2 );
wys_slider_title 是元框内的字段,其中包含幻灯片的标题、图像和链接字段。同样,当我在本地主机或主机提供程序上使用此选项时,不会出现错误,但我客户端的主机提供程序不同,会抛出此错误
因此,我无法发布任何内容,我被告知我的内容将"Submitted for review", 尽管我是网站的管理员。

有谁能帮助解决可能出现的问题吗?

编辑:有人要求我将函数发布到wys_slider_title 已声明。这是用于运行post类型的完整脚本:

// Stories custom post type

add_action(\'init\', \'wys_sliders\');

function wys_sliders() {

    $labels = array(
        \'name\' => _x(\'Front Slider\', \'post type general name\'),
        \'singular_name\' => _x(\'Front Slider\', \'post type singular name\'),
        \'add_new\' => _x(\'Add New\', \'post type item\'),
        \'add_new_item\' => __(\'Add New Slide\'),
        \'edit_item\' => __(\'Edit Slide\'),
        \'new_item\' => __(\'New Slide\'),
        \'view_item\' => __(\'View Slide\'),
        \'search_items\' => __(\'Search Slides\'),
        \'not_found\' =>  __(\'Nothing found\'),
        \'not_found_in_trash\' => __(\'Nothing found in Trash\'),
        \'parent_item_colon\' => \'\'
    );

    $args = array(
        \'labels\' => $labels,
        \'public\' => true,
        \'publicly_queryable\' => true,
        \'show_ui\' => true,
        \'query_var\' => true,
        \'menu_icon\' => \'dashicons-slides\',
        \'capability_type\' => \'post\',
        \'hierarchical\' => false,
        \'menu_position\' => 24,
        \'supports\' => false,
        \'can_export\' => true,
        \'show_in_menu\' => true,
        \'has_archive\' => false,
      ); 

    register_post_type( \'slider\' , $args );
    flush_rewrite_rules();
}

add_action("admin_init", "wys_slide_admin_init");
function wys_slide_admin_init(){
  add_meta_box("mb_wys_slides", "Slides", "wys_slides_display", "slider", "normal", "high");
}
add_action( \'admin_enqueue_scripts\', \'wys_slides_scripts\' );
function wys_slides_scripts(){
    global $post_type;
    if ( $post_type == "slider" ){
        wp_enqueue_style(\'slider-css-styles\', get_template_directory_uri().\'/inc/cpt/slides.css\');
    }
}

function wys_slides_display(){
    $source = get_post_meta( get_the_ID(), \'selected_source\', true );
    $image = get_post_meta( get_the_ID(), \'wys_slider_image\', true );
    $video = get_post_meta( get_the_ID(), \'video_preview\', true );
    $title = get_post_meta( get_the_ID(), \'wys_slider_title\', true );
    $caption = get_post_meta( get_the_ID(), \'wys_slider_caption\', true );
    $link = get_post_meta( get_the_ID(), \'wys_slider_link\', true );
    $target = get_post_meta( get_the_ID(), \'wys_link_target\', true );
?>
<script>
function resetItAll(){
    // Clear fields
    $(\'#image-url\').val(\'\');
    $(\'#video-url\').val(\'\');
    $(\'#wys-slider-image\').val(\'\');
    $(\'#video-preview\').val(\'\');

    // Clear Uploaded Image
    $(\'#slide-upload\').removeClass(\'hasimage\');
    $(\'#slide-upload\').css(\'background-image\', \'none\');

    // Clear Image by URL
    $(\'#slide-url\').removeClass(\'hasimage\');
    $(\'#slide-url\').css(\'background-image\', \'none\');
    $(\'#slide-url .replace-image\').hide();
    $(\'#slide-url .form-wrap\').show();

    // Clear Video
    $(\'#slide-video\').removeClass(\'hasimage\');
    $(\'#slide-video\').css(\'background-image\', \'none\');
    $(\'slide-video .replace-video\').hide();
    $(\'#slide-video .form-wrap\').show();
}
(function($){
    $.fn.extend({
        limiter: function(elem){
            $(this).on(\'keyup focus\', function(){
               setCount(this, elem); 
            });
            function setCount(src, elem){
                var chars = src.value.length;
                var limit = $(src).attr(\'maxlength\');
                if ( chars > limit ){
                    src.value = src.value.substr(0, limit);
                    chars = limit;
                }
                var charsRemaining = limit - chars;
                if ( charsRemaining <= (limit*.2) ) { var charsLeft = \'<span class="charlimit-warning">\'+charsRemaining+\'</span>\'; } else { var charsLeft = charsRemaining; }
                $(elem).html( charsLeft + \'/\' + limit );
            }
            setCount($(this)[0], elem);
        }
    });
})(jQuery);
jQuery(document).ready(function($){
    $(\'.image-src a\').click(function(e){
        e.preventDefault();
        var tab = $(this).data(\'tab\');
        $(\'.image-src a\').removeClass(\'selected\');
        $(\'.tab-content\').removeClass(\'show-tab\');

        $(this).addClass(\'selected\');
        $("#slide-"+tab).addClass(\'show-tab\');
        $(\'#selected-source\').val(tab);
    });
    $(\'#upload-image\').click(function(e) {
      e.preventDefault();
      var custom_uploader = wp.media({
        title: \'Select Slider Image\',
        button: {
            text: \'Select Image\'
        },
        multiple: false  // Set this to true to allow multiple files to be selected
      })
      .on(\'select\', function() {
        var attachment = custom_uploader.state().get(\'selection\').first().toJSON();
        resetItAll();
        $(\'#slide-upload\').addClass(\'hasimage\');
        $(\'#slide-upload\').css(\'background-image\', \'url(\'+attachment.sizes.large.url+\')\');
        $(\'#wys-slider-image\').val(attachment.id);
      })
      .open();
    });
    $(\'#fetch-image\').click(function(e){
        e.preventDefault();
        var imagesrc = $(\'#image-url\').val();
        $("<img>", {
            src: imagesrc,
            error: function(){
                $(\'.error-msg .error-text\').html(\'The URL you provided is not a valid image.\');
                $(\'.error-msg\').show(0, function(){
                    $(\'#fetch-image\').click(function(){
                        $(\'.error-msg\').fadeOut(300);
                    });
                    $(\'.error-msg\').delay(7000).fadeOut(300);
                });
            },
            load: function(){
                resetItAll();
                $(\'#slide-url\').addClass(\'hasimage\');
                $(\'#slide-url\').css(\'background-image\', \'url(\'+imagesrc+\')\');
                $(\'#wys-slider-image\').val(imagesrc);
                $(\'#slide-url .form-wrap\').hide();
                $(\'#slide-url .replace-image\').show();
            }
        });
    });
    $(\'#replace-image\').click(function(e){
        e.preventDefault();
        $(\'#image-url\').val(\'\').focus();
        $(\'#slide-url .replace-image\').hide();
        $(\'#slide-url .form-wrap\').show();
    });
    $(\'#fetch-video\').click(function(e){
        e.preventDefault();
        var videosrc = $(\'#video-url\').val();
        $.ajax({
            method: "POST",
            url: \'<?php echo get_template_directory_uri(); ?>/inc/cpt/inc.videoimg.php\',
            data: { src: videosrc },
            success: function(data){
                if ( data == \'invalid.src\' ) {
                    $(\'.error-msg .error-text\').html(\'Please use a video from YouTube or Vimeo.\');
                    $(\'.error-msg\').show(0, function(){
                        $(\'#fetch-video\').click(function(){
                            $(\'.error-msg\').fadeOut(300);
                        });
                        $(\'.error-msg\').delay(7000).fadeOut(300);
                    });
                } else {
                    resetItAll();
                    $(\'#slide-video\').addClass(\'hasimage\');
                    $(\'#slide-video\').css(\'background-image\', \'url(\'+data+\')\');
                    $(\'#wys-slider-image\').val(videosrc);
                    $(\'#video-preview\').val(data);
                    $(\'#slide-video .form-wrap\').hide();
                    $(\'#slide-video .replace-video\').show();
                }
            },
            error: function( xhr, status, error){
                if (xhr.status > 0) console.log(\'got error: \'+status); // Status 0 - when load is interrupted
            }
        });
    });
    $(\'#replace-video\').click(function(e){
        e.preventDefault();
        $(\'#video-url\').val(\'\').focus();
        $(\'slide-video .replace-video\').hide();
        $(\'#slide-video .form-wrap\').show();
    });
    $(\'#link-target\').click(function(e){
        e.preventDefault();
        $(this).toggleClass(\'selected\');
        if ( $(this).hasClass(\'selected\') ) {
            $(\'#wys-link-target\').val(\'1\');
        } else {
            $(\'#wys-link-target\').val(\'0\');
        }
    });
    $(\'#slide-title\').limiter(\'#slide-title-limit\');
    $(\'#slide-caption\').limiter(\'#slide-caption-limit\');
});
</script>
<div class="wys-slides">
  <div class="slide" id="slide">
    <div class="body">
      <div class="slide-image-wrap">
        <div class="error-msg" style="display: none;">
          <span class="dashicons dashicons-warning"></span>
          <span class="error-text">This is an error message.</span>
        </div>
        <div id="slide-upload" class="uploaded image tab-content <?php if ( $source == \'upload\' && $image ) { $imgid = wp_get_attachment_image_src( $image, \'large\' ); echo \'hasimage show-tab" style="background-image: url(\'.$imgid[0].\');\'; } if ( !$source ) { echo \'show-tab\'; } ?>">
          <a href="#upload" class="upload" id="upload-image"><span class="icon dashicons dashicons-upload"></span>
            Upload Image</a>
        </div>
        <div id="slide-url" class="from-url image tab-content <?php if ( $source == \'url\' && $image ) { echo \'hasimage show-tab" style="background-image: url(\'.$image.\');\'; } ?>">
          <div class="form-wrap" <?php if ( $source == \'url\' && $image ) { echo \'style="display: none;"\'; } ?>>
            <label>Image URL</label>
            <input type="url" class="image-url" id="image-url" value="<?php if ( $source == \'url\' && $image ) { echo $image; } ?>" />
            <input type="button" name="fetch-image" id="fetch-image" value="Get Image" />
          </div>
          <div class="replace-image hasimage" <?php if ( $source == \'url\' && !$image ) { echo \'style="display: none;"\'; } ?>>
            <a href="#replace-image" id="replace-image" class="upload"><span class="icon dashicons dashicons-controls-repeat"></span>
              Replace Image</a>
          </div>
        </div>
        <div id="slide-video" class="video image tab-content <?php if ( $source == \'video\' && $image ) { echo \'hasimage show-tab" style="background-image: url(\'.$video.\');\'; } ?>">
          <div class="form-wrap" <?php if ( $source == \'video\' && $image ) { echo \'style="display: none;"\'; } ?>>
            <label>Video URL <span>Youtube or Vimeo only</span></label>
            <input type="url" class="video-url" id="video-url" value="<?php if ( $source == \'video\' && $image ) { echo $video; } ?>" />
            <input type="button" name="fetch-video" id="fetch-video" value="Get Video" />
          </div>
          <div class="replace-video hasimage" <?php if ( $source == \'video\' && !$image ) { echo \'style="display: none;"\'; } ?>>
            <a href="#replace-video" id="replace-video" class="upload"><span class="icon dashicons dashicons-controls-repeat"></span>
              Replace Video</a>
          </div>
        </div>
        <div class="image-src">
          <a href="#upload-image" class="first <?php if ( $source == "upload" || !$source ) { echo \'selected\'; } ?>" data-tab="upload"><span class="dashicons dashicons-upload"></span>
            Upload</a>
          <a href="#from-url" class="last <?php if ( $source == "url" ) { echo \'selected\'; } ?>" data-tab="url"><span class="dashicons dashicons-admin-links"></span>
            From URL</a>
        </div>
      </div>
      <div class="slide-display-data">
        <div class="row slide-title">
          <div class="field">
            <label>
              Slide Title
              <span class="notes" id="slide-title-limit"></span>
            </label>
            <input type="text" class="slide-title" name="wys_slider_title" id="slide-title" maxlength="50" placeholder="Enter Title" value="<?php echo $title; ?>" />
          </div>
        </div>
        <div class="row slide-caption">
          <div class="field">
            <label>
              Slide Caption
              <span class="notes" id="slide-caption-limit"></span>
            </label>
            <textarea class="slide-caption" name="wys_slider_caption" maxlength="140" id="slide-caption"><?php echo $caption; ?></textarea>
          </div>
        </div>
        <div class="row slide-link">
          <div class="field">
            <label>
              Slide Link
              <span class="notes">eg. http://www.google.com</span>
            </label>
            <input type="text" class="slide-link" name="wys_slider_link" value="<?php echo $link; ?>" />
          </div>
          <a href="#new-tab" id="link-target" class="link-target <?php if ( $target == "1" ) { echo \'selected\'; } else { } ?>" title="Open link in new tab"><span class="icon dashicons dashicons-external"></span></a>
        </div>
        <input type="hidden" class="wys-link-target" id="wys-link-target" name="wys_link_target" value="<?php if ( !$target ) { echo \'0\'; } else { echo $target; } ?>" />
        <input type="hidden" id="selected-source" name="selected_source" value="<?php if ( !$source ) { echo \'upload\'; } else { echo $source; } ?>" />
        <input type="hidden" id="wys-slider-image" name="wys_slider_image" value="<?php echo $image; ?>" />
        <input type="hidden" id="video-preview" name="video_preview" value="<?php echo $video; ?>" />
      </div>
      <div class="clear"></div>
    </div>
  </div>
</div>
<?php
}

function wys_slide_title( $data , $postarr ) {
    if( $data[\'post_type\'] == \'slider\' ) {
        $slide_title = $_POST[\'wys_slider_title\'];
        $new_title = $slide_title;
        // Set slug date
        $post_date = date(\'Ymd-His\');
        // $post_slug = sanitize_title_with_dashes($post_date, \'\', $context = \'save\');
        $post_slugsan = sanitize_title($post_date);
        $data[\'post_title\'] = $new_title;
        $data[\'post_name\'] = $post_slugsan;  
    }
    return $data;
}
add_filter( \'wp_insert_post_data\' , \'wys_slide_title\' , \'99\', 2 );

add_action(\'save_post\', \'wys_slides_save_details\');

function wys_slides_save_details(){
  global $post;

  update_post_meta($post->ID, "video_preview", $_POST["video_preview"]);
  update_post_meta($post->ID, "wys_slider_image", $_POST["wys_slider_image"]);
  update_post_meta($post->ID, "selected_source", $_POST["selected_source"]);
  update_post_meta($post->ID, "wys_link_target", $_POST["wys_link_target"]);
  update_post_meta($post->ID, "wys_slider_link", $_POST["wys_slider_link"]);
  update_post_meta($post->ID, "wys_slider_caption", strip_tags($_POST["wys_slider_caption"]));
  update_post_meta($post->ID, "wys_slider_title", strip_tags($_POST["wys_slider_title"]));

}

3 个回复
SO网友:user6552940

我建议进行以下改进,以提高代码的可读性,并便于以后维护。

假设您已删除title 使用以下函数从自定义帖子类型:

remove_post_type_support( \'slider\', \'title\' )
现在如果您使用name="post_title" 而不是name="wys_slider_title"*这有助于您避免使用wp_insert_post_data 附加过滤器
*由于您没有使用wp_update_post 功能,您不必担心save_post 无限循环。

在保存任何数据之前,请确保其中没有恶意内容。幸运的是,WordPress为Data Validation

// Use:
update_post_meta( $post_id, \'my_meta_box_text\', wp_kses( $_POST[\'my_meta_box_text\'], $allowed ) );
// Instead of:
update_post_meta( $post_id, \'my_meta_box_text\', $_POST[\'my_meta_box_text\'] );
使用save_post_{$post_type} 而不是普通的save_post, 这有助于避免不必要的IF 陈述,例如在你的情况下add_action( \'save_post_slider\', \'wys_slides_save_details\' );

您不需要将逻辑围绕IF 声明

if( $post_type == \'slider\' ) {...CODE...}
save_post_slider 将仅运行Slider 岗位类型。

SO网友:Laxmana

我会删除wys_slide_title 过滤并将逻辑移到内部save_post 行动还没有测试,但应该可以工作。

add_action(\'save_post\', \'wys_slides_save_details\');

function wys_slides_save_details($post_id){

  $post = get_post($post_id);

  if( $post->post_type == \'slider\' ) {

    update_post_meta($post->ID, "video_preview", $_POST["video_preview"]);
    update_post_meta($post->ID, "wys_slider_image", $_POST["wys_slider_image"]);
    update_post_meta($post->ID, "selected_source", $_POST["selected_source"]);
    update_post_meta($post->ID, "wys_link_target", $_POST["wys_link_target"]);
    update_post_meta($post->ID, "wys_slider_link", $_POST["wys_slider_link"]);
    update_post_meta($post->ID, "wys_slider_caption", strip_tags($_POST["wys_slider_caption"]));
    update_post_meta($post->ID, "wys_slider_title", strip_tags($_POST["wys_slider_title"]));

    $slide_title = sanitize_text_field($_POST[\'wys_slider_title\']);
    $new_title = $slide_title;
    // Set slug date
    $post_date = date(\'Ymd-His\');
    // $post_slug = sanitize_title_with_dashes($post_date, \'\', $context = \'save\');
    $post_slugsan = sanitize_title($post_date);  

    /* To avoid infinite loops */

    remove_action( \'save_post\', \'wys_slides_save_details\' );

    wp_update_post( array( \'post_title\' => $new_title, \'post_name\' => $post_slugsan ) );

    add_action( \'save_post\', \'wys_slides_save_details\' );

  }

}

SO网友:shishir mishra

您应该使用save\\u post{post\\u type}而不是save\\u post。连接到此操作,您不必检查帖子类型(即:if($slug!=$\\u post[\'post\\u type\'))。

阅读下面提到的文章同样。。。

https://codex.wordpress.org/Plugin_API/Action_Reference/save_post

相关推荐

正在尝试将Get_the_Title挂钩添加到该行

您好,创建联系人表单。正在尝试将get\\u the\\u title()添加到此代码行中:<?php echo \'<textarea style=\"margin-left: 15px; width: 246px;\" rows=\"3\" cols=\"28\" placeholder=\"I am interested in:\" name=\"cf-message\">\' . ( isset( $_POST[\"cf-message\"] ) ? esc_attr( $_PO