Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Nerdies24/792fcb77014724f5c45ee7f92acc2487 to your computer and use it in GitHub Desktop.
Save Nerdies24/792fcb77014724f5c45ee7f92acc2487 to your computer and use it in GitHub Desktop.
Meta Box und Felder generieren in GeneratePress und GenerateBlocks

Kundenprojekte professioneller gestalten mit Must Use Plugins!

Must Use Plugins sind Plugins in WordPress, die immer aktiviert sind und nicht deaktiviert werden können. Sie werden normalerweise verwendet, um Funktionen bereitzustellen, die für das ordnungsgemäße Funktionieren einer Website erforderlich sind, wie z.B. Sicherheitsfunktionen oder Caching. Must Use Plugins werden in einem speziellen Verzeichnis auf dem Server gespeichert und automatisch von WordPress geladen, ohne dass der Benutzer sie manuell aktivieren muss.

  1. Post Typ Generator: https://generatewp.com
  2. Meta Box Generator: https://wp-skills.com/generators

Fertiges Plugin und Excel Tabelle downloaden


Mein erzeugter Code aus dem Video

<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Beenden, wenn direkt zugegriffen wird.
}

// Benutzerdefinierten Beitragstyp registrieren - Erstellt mit https://generatewp.com/post-type

if ( ! function_exists('prefix_create_seminar_dwp') ) {

    // Register Custom Post Type
    function prefix_create_seminar_dwp() {
    
        $labels = array(
            'name'                  => _x( 'Seminare', 'Post Type General Name', 'text_domain' ),
            'singular_name'         => _x( 'Seminar', 'Post Type Singular Name', 'text_domain' ),
            'menu_name'             => __( 'Seminare', 'text_domain' ),
            'name_admin_bar'        => __( 'Seminare', 'text_domain' ),
            'archives'              => __( 'Archiv', 'text_domain' ),
            'attributes'            => __( 'Attribute', 'text_domain' ),
            'parent_item_colon'     => __( 'Übergeordnetes Seminar', 'text_domain' ),
            'all_items'             => __( 'Alle Seminare', 'text_domain' ),
            'add_new_item'          => __( 'Neues Seminar', 'text_domain' ),
            'add_new'               => __( 'Neu hinzufügen', 'text_domain' ),
            'new_item'              => __( 'Neues Seminar', 'text_domain' ),
            'edit_item'             => __( 'Seminar bearbeiten', 'text_domain' ),
            'update_item'           => __( 'Seminar aktualisieren', 'text_domain' ),
            'view_item'             => __( 'Seminar anzeigen', 'text_domain' ),
            'view_items'            => __( 'Seminare anzeigen', 'text_domain' ),
            'search_items'          => __( 'Seminar suchen', 'text_domain' ),
            'not_found'             => __( 'Nichts gefunden', 'text_domain' ),
            'not_found_in_trash'    => __( 'Nicht im Papierkorb gefunden', 'text_domain' ),
            'featured_image'        => __( 'Ausgewähltes Bild', 'text_domain' ),
            'set_featured_image'    => __( 'Ausgewähltes Bild einstellen', 'text_domain' ),
            'remove_featured_image' => __( 'Ausgewähltes Bild entfernen', 'text_domain' ),
            'use_featured_image'    => __( 'Als Hauptbild verwenden', 'text_domain' ),
            'insert_into_item'      => __( 'In Artikel einfügen', 'text_domain' ),
            'uploaded_to_this_item' => __( 'Zu diesem Artikel hochgeladen', 'text_domain' ),
            'items_list'            => __( 'Liste der Artikel', 'text_domain' ),
            'items_list_navigation' => __( 'Navigation in der Artikelliste', 'text_domain' ),
            'filter_items_list'     => __( 'Liste der Elemente filtern', 'text_domain' ),
        );
        $rewrite = array(
            'slug'                  => 'seminare',
            'with_front'            => true,
            'pages'                 => true,
            'feeds'                 => true,
        );
        $args = array(
            'label'                 => __( 'Seminar', 'text_domain' ),
            'description'           => __( '', 'text_domain' ),
            'labels'                => $labels,
            'supports'              => array( 'title', 'editor' ),
            'taxonomies'            => array( 'category', 'post_tag' ),
            'hierarchical'          => false,
            'public'                => true,
            'show_ui'               => true,
            'show_in_menu'          => true,
            'menu_position'         => 5,
            'menu_icon'             => 'dashicons-networking',
            'show_in_admin_bar'     => true,
            'show_in_nav_menus'     => true,
            'can_export'            => true,
            'has_archive'           => 'seminare',
            'exclude_from_search'   => false,
            'publicly_queryable'    => true,
            'rewrite'               => $rewrite,
            'capability_type'       => 'page',
            'show_in_rest'          => true,
        );
        register_post_type( 'prefix_seminare', $args );
    
    }
    add_action( 'init', 'prefix_create_seminar_dwp', 0 );
    
    }

// https://wp-skills.com
// Meta Box Class: SeminarinformationenMetaBox
// Get the field value: $metavalue = get_post_meta( $post_id, $field_id, true );
class SeminarinformationenMetaBox{

	private $screen = array(
		'prefix_seminare',
                        
	);

	private $meta_fields = array(
                array(
                    'label' => 'Seminar ID:',
                    'id' => 'seminar-id',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Seminar Titel:',
                    'id' => 'seminar-titel',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Beschreibung des Seminares:',
                    'id' => 'seminar-beschreibung',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Ziel des Seminares:',
                    'id' => 'seminar-ziel',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Referent/Trainer:',
                    'id' => 'seminar-trainer',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Seminar Datum:',
                    'id' => 'seminar-datum',
                    'type' => 'date',
                ),
    
                array(
                    'label' => 'Seminar Uhrzeit:',
                    'id' => 'seminar-uhrzeit',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Seminar Ort:',
                    'id' => 'seminar-ort',
                    'type' => 'textarea',
                ),
    
                array(
                    'label' => 'Seminar Pausen:',
                    'id' => 'seminar-pausen',
                    'type' => 'textarea',
                ),
    
                array(
                    'label' => 'Seminar Dauer:',
                    'id' => 'seminar-dauer',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Maximale Teilnehmerzahl:',
                    'id' => 'seminar-maximale-teilnehmerzahl',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Art des Seminares:',
                    'id' => 'seminar-art',
                    'type' => 'select',
                    'options' => array(
                        'Tagesseminar',
                        '3 Tages-Seminare',
                        'Onlineseminar',
                        'Inhouse Seminar'
                    )
                ),
    
                array(
                    'label' => 'Zielgruppe des Seminares:',
                    'id' => 'seminar-zielgruppe',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Seminar Voraussetzung:',
                    'id' => 'seminar-voraussetzung',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Seminar Kosten:',
                    'id' => 'seminar-kosten',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Teilnahmebescheinigung: ',
                    'id' => 'seminar-teilnahmebescheinigung',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Seminar Materialien: ',
                    'id' => 'seminar-materialien',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Anforderungen an die Teilnehmer:',
                    'id' => 'seminar-anforderungen',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Seminar Anmeldefrist:',
                    'id' => 'seminar-anmeldefrist',
                    'type' => 'date',
                ),
    
                array(
                    'label' => 'Sprache des Seminares:',
                    'id' => 'seminar-sprache',
                    'type' => 'text',
                ),
    
                array(
                    'label' => 'Seminar Bild:',
                    'id' => 'seminar-bild',
                    'type' => 'media',
                    'returnvalue' => 'url'
                ),
    
                array(
                    'label' => 'Seminar Bild Trainer:',
                    'id' => 'seminar-bild-trainer',
                    'type' => 'media',
                    'returnvalue' => 'url'
                )

	);

	public function __construct() {
		add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
                add_action( 'admin_footer', array( $this, 'media_fields' ) );
		add_action( 'save_post', array( $this, 'save_fields' ) );
	}

	public function add_meta_boxes() {
		foreach ( $this->screen as $single_screen ) {
			add_meta_box(
				'Seminarinformationen',
				__( 'Seminarinformationen', '' ),
				array( $this, 'meta_box_callback' ),
				$single_screen,
				'advanced',
				'high'
			);
		}
	}

	public function meta_box_callback( $post ) {
		wp_nonce_field( 'Seminarinformationen_data', 'Seminarinformationen_nonce' );
                echo 'Füllen Sie bitte hier die Informationen zu diesem Seminar aus!';
		$this->field_generator( $post );
	}
        public function media_fields() {
            ?><script>
                jQuery(document).ready(function($){
                    if ( typeof wp.media !== 'undefined' ) {
                        var _custom_media = true,
                        _orig_send_attachment = wp.media.editor.send.attachment;
                        $('.new-media').click(function(e) {
                            var send_attachment_bkp = wp.media.editor.send.attachment;
                            var button = $(this);
                            var id = button.attr('id').replace('_button', '');
                            _custom_media = true;
                                wp.media.editor.send.attachment = function(props, attachment){
                                if ( _custom_media ) {
                                    if ($('input#' + id).data('return') == 'url') {
                                        $('input#' + id).val(attachment.url);
                                    } else {
                                        $('input#' + id).val(attachment.id);
                                    }
                                    $('div#preview'+id).css('background-image', 'url('+attachment.url+')');
                                } else {
                                    return _orig_send_attachment.apply( this, [props, attachment] );
                                };
                            }
                            wp.media.editor.open(button);
                            return false;
                        });
                        $('.add_media').on('click', function(){
                            _custom_media = false;
                        });
                        $('.remove-media').on('click', function(){
                            var parent = $(this).parents('td');
                            parent.find('input[type="text"]').val('');
                            parent.find('div').css('background-image', 'url()');
                        });
                    }
                });
            </script><?php
        }

	public function field_generator( $post ) {
		$output = '';
		foreach ( $this->meta_fields as $meta_field ) {
			$label = '<label for="' . $meta_field['id'] . '">' . $meta_field['label'] . '</label>';
			$meta_value = get_post_meta( $post->ID, $meta_field['id'], true );
			if ( empty( $meta_value ) ) {
				if ( isset( $meta_field['default'] ) ) {
					$meta_value = $meta_field['default'];
				}
			}
			switch ( $meta_field['type'] ) {
                                case 'media':
                                    $meta_url = '';
                                        if ($meta_value) {
                                            if ($meta_field['returnvalue'] == 'url') {
                                                $meta_url = $meta_value;
                                            } else {
                                                $meta_url = wp_get_attachment_url($meta_value);
                                            }
                                        }
                                    $input = sprintf(
                                        '<input style="display:none;" id="%s" name="%s" type="text" value="%s"  data-return="%s"><div id="preview%s" style="margin-right:10px;border:1px solid #e2e4e7;background-color:#fafafa;display:inline-block;width: 100px;height:100px;background-image:url(%s);background-size:cover;background-repeat:no-repeat;background-position:center;"></div><input style="width: 19%%;margin-right:5px;" class="button new-media" id="%s_button" name="%s_button" type="button" value="Select" /><input style="width: 19%%;" class="button remove-media" id="%s_buttonremove" name="%s_buttonremove" type="button" value="Clear" />',
                                        $meta_field['id'],
                                        $meta_field['id'],
                                        $meta_value,
                                        $meta_field['returnvalue'],
                                        $meta_field['id'],
                                        $meta_url,
                                        $meta_field['id'],
                                        $meta_field['id'],
                                        $meta_field['id'],
                                        $meta_field['id']
                                    );
                                    break;


                                case 'select':
                                    $input = sprintf(
                                        '<select id="%s" name="%s">',
                                        $meta_field['id'],
                                        $meta_field['id']
                                    );
                                    foreach ( $meta_field['options'] as $key => $value ) {
                                        $meta_field_value = !is_numeric( $key ) ? $key : $value;
                                        $input .= sprintf(
                                            '<option %s value="%s">%s</option>',
                                            $meta_value === $meta_field_value ? 'selected' : '',
                                            $meta_field_value,
                                            $value
                                        );
                                    }
                                    $input .= '</select>';
                                    break;

                                case 'textarea':
                                    $input = sprintf(
                                        '<textarea style="" id="%s" name="%s" rows="5">%s</textarea>',
                                        $meta_field['id'],
                                        $meta_field['id'],
                                        $meta_value
                                    );
                                    break;
            
				default:
                                    $input = sprintf(
                                        '<input %s id="%s" name="%s" type="%s" value="%s">',
                                        $meta_field['type'] !== 'color' ? 'style="width: 100%"' : '',
                                        $meta_field['id'],
                                        $meta_field['id'],
                                        $meta_field['type'],
                                        $meta_value
                                    );
			}
			$output .= $this->format_rows( $label, $input );
		}
		echo '<table class="form-table"><tbody>' . $output . '</tbody></table>';
	}

	public function format_rows( $label, $input ) {
		return '<tr><th>'.$label.'</th><td>'.$input.'</td></tr>';
	}

	public function save_fields( $post_id ) {
		if ( ! isset( $_POST['Seminarinformationen_nonce'] ) )
			return $post_id;
		$nonce = $_POST['Seminarinformationen_nonce'];
		if ( !wp_verify_nonce( $nonce, 'Seminarinformationen_data' ) )
			return $post_id;
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
			return $post_id;
		foreach ( $this->meta_fields as $meta_field ) {
			if ( isset( $_POST[ $meta_field['id'] ] ) ) {
				switch ( $meta_field['type'] ) {
					case 'email':
						$_POST[ $meta_field['id'] ] = sanitize_email( $_POST[ $meta_field['id'] ] );
						break;
					case 'text':
						$_POST[ $meta_field['id'] ] = sanitize_text_field( $_POST[ $meta_field['id'] ] );
						break;
				}
				update_post_meta( $post_id, $meta_field['id'], $_POST[ $meta_field['id'] ] );
			} else if ( $meta_field['type'] === 'checkbox' ) {
				update_post_meta( $post_id, $meta_field['id'], '0' );
			}
		}
	}
}

if (class_exists('SeminarinformationenMetabox')) {
	new SeminarinformationenMetabox;
};

Dieser Gist gehört zur Facebook Gruppe: https://www.facebook.com/groups/deinwordpressprojekt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment