@Combat7

Как сделать доп поля в кастомных постах вордпресс?

В общем создал дополнительный тип записей вордпрес.
Для них мне нужно сделать штук 5 дополнительных полей, причем чтобы они были сразу при создании записи, и не приходилось их добавлять по новой (то есть вшиты в мой тип записей)
  • Вопрос задан
  • 1479 просмотров
Решения вопроса 2
Вы когда регистрируете тип поста, в его опциях нужно указывать что ему доступны кастомные поля:

add_action( 'init', 'true_register_post_type_init' ); // Использовать функцию только внутри хука init
 
function true_register_post_type_init() {
	$labels = array(
		'name' => 'Компании',
		'singular_name' => 'Компанию', // админ панель Добавить->Функцию
		'add_new' => 'Добавить компанию',
		'add_new_item' => 'Добавить новую компанию', // заголовок тега <title>
		'edit_item' => 'Редактировать компанию',
		'new_item' => 'Новая компания',
		'all_items' => 'Все компании',
		'view_item' => 'Просмотр компании на сайте',
		'search_items' => 'Искать компании',
		'not_found' =>  'Компаний не найдено.',
		'not_found_in_trash' => 'В корзине нет компаний.',
		'menu_name' => 'Компании' // ссылка в меню в админке
	);
	$args = array(
		'labels' => $labels,
		'public' => true,
		'show_ui' => true, // показывать интерфейс в админке
		'has_archive' => true,
		'exclude_from_search' => true, 
		'menu_icon' => 'dashicons-groups', // иконка в меню
		'menu_position' => 100, // порядок в меню
		'supports' => array( 'title', 'editor', 'comments', 'author', 'thumbnail','custom-fields')
	);
	register_post_type('company', $args);
}

Обратите внимание на эту строку:
'supports' => array( 'title', 'editor', 'comments', 'author', 'thumbnail','custom-fields')

В конце у вас скорее всего просто не прописано: custom-fields
Ответ написан
deniscopro
@deniscopro Куратор тега WordPress
WordPress-разработчик, denisco.pro
Плагин Advanced Custom Fields уже пробовали?
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
Gori4ka
@Gori4ka
WordPress Developer
вот можете по пробывать воспользоваться моим классом
<?php
if (!class_exists('Metabox_Handler')) {

    /**
     * @doc en https://developer.wordpress.org/reference/functions/add_meta_box/
     * @doc ru http://wp-kama.ru/function/add_meta_box/
     *
     * @param string $this ->args->slug      (string) (Required) Meta box ID (used in the 'id' attribute for the meta box).
     * @param string $this ->args->title     (string) (Required) Title of the meta box.
     * @param mixed $this ->args->screen     (string|array|WP_Screen) (Optional) The screen or screens on which to show the box (such as a post type, 'link', or 'comment'). Accepts a single screen ID, WP_Screen object, or array of screen IDs. Default is the current screen.
     *                                      Default value: null
     * @param string $this ->args->context   (string) (Optional) The context within the screen where the boxes should display. Available contexts vary from screen to screen. Post edit screen contexts include 'normal', 'side', and 'advanced'. Comments screen contexts include 'normal' and 'side'. Menus meta boxes (accordion sections) all use the 'side' context. Global
     *                                      Default value: 'advanced'
     * @param string $this ->args->priority  (string) (Optional) The priority within the context where the boxes should show ('high', 'low').
     *                                      Default value: 'default'
     *
     */
    abstract class Metabox_Handler
    {

        public $slug;
        public $slug_nonce;
        public $args;
        private static $instance;

        /**
         *
         * @example Using this Class
         *  class SomeClass extends Metabox_Handler {
         *
         *
         *      function __construct() {
         *          $this->args = new stdClass();
         *          $this->args->slug = 'fb_gallary_';
         *          $this->args->title = __('Album Bilden', 'pfalz');
         *          $this->args->screen = 'fb_gallary';
         *          $this->args->context = 'normal';
         *          $this->args->priority = 'high';
         *          parent::__construct();
         *      }
         *
         *      public function backend($post) {
         *
         *      }
         *
         *      public function update($post_id) {
         *
         *      }
         *
         *  }
         *
         *  new SomeClass();
         *
         */
        function __construct()
        {
            if (isset($_GET['post']) || isset($_POST['post_ID'])) {
                $this->init_args();
                $this->init_metabox();
            }
        }

        private function init_args()
        {
            if (isset($_GET['post'])) {
                $this->ID = $_GET['post'];
            } else if (isset($_POST['post_ID'])) {
                $this->ID = $_POST['post_ID'];
            }
        }

        public function init_metabox()
        {
            global $current_screen;
            $this->slug = $this->args->slug;
            $this->slug_nonce = $this->args->slug . 'nonce';
            add_action('add_meta_boxes', array($this, 'add'), 1);
            add_action('save_post', array($this, 'privat_update'), 0);
            add_action("admin_enqueue_scripts", array($this, 'admin_scripts'));
        }

        function add()
        {

            $defaults = array(
                'id' => $this->args->slug . '_fields',
                'title' => __('Some Title', 'pfalz'),
                'screen' => 'any',
                'context' => 'normal',
                'priority' => 'default',
            );

            $args = wp_parse_args($this->args, $defaults);
            add_meta_box(
                $args['id'], $args['title'], array($this, 'private_backend'), $args['screen'], $args['context'], $args['priority']
            );
        }

        function private_backend($post)
        {
            $this->backend($post);
            ?>
            <input type="hidden" name="<?php echo $this->slug_nonce; ?>" class="widefat"
                   value="<?php echo wp_create_nonce(__FILE__); ?>"/>
            <?php
        }

        function privat_update($post_id)
        {
            if (!wp_verify_nonce(@$_POST[$this->slug_nonce], __FILE__))
                return false;
            if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
                return false;
            if (!current_user_can('edit_post', $post_id))
                return false;

            $this->update($post_id);

            return $post_id;
        }

        function admin_scripts()
        {

        }

        abstract public function backend($post);

        abstract public function update($post_id);
    }

}

вот можно можно ещё разных примеров найти wp--kama
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы