Wordpress set default title when creating a new cu

2019-08-28 20:39发布

I have a custom post type with just two (text)fields: an ISBN number and a youtube url by using 'supports' => array('title') when creating my custom post type.

The problem is, I don't need a title. So when I save my post, I made it so that the title becomes the ISBN number.

  add_filter('wp_insert_post_data', array($this, 'change_title'), 99, 2);

  function change_title($data, $postarr) {
    if ($data['post_type'] == 'book_video') {
      // If it is our form has not been submitted, so we dont want to do anything
      if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return $data;

      // Verify this came from the our screen and with proper authorization because save_post can be triggered at other times
      if (!isset($_POST['wp_meta_box_nonce']))
        return $data;

      // Combine address with term
      $title = $_POST['_bv_isbn'];
      $data['post_title'] = $title;
    }
    return $data;
  }

This works, but the problem is, when I save the post WITHOUT prefilling a title (anything at all) the post is not saved, the title change function is not called, and all of my fields are reset.

Is it possible to set a default value to the title and hide it ?

1条回答
Viruses.
2楼-- · 2019-08-28 21:00

When you register your custom post type, you can set what it supports, including the title.

When you call register_post_type(), add another entry to $args called supports and set it's value to an array. You can then pass a list of elements you want that post type to support. The default is 'title' and 'editor', but there are a host of options to choose from.

For example:

<?php 
  register_post_type( 
    "myCustomPostType", 
    array(
      'supports' : array(
        'editor',
        'author',
        'custom-fields'
      )
    )
  )
?>

So long as you miss out title then you won't have to define one for each post.

For more information, visit this page: http://codex.wordpress.org/Function_Reference/register_post_type#Arguments

查看更多
登录 后发表回答