Outils pour utilisateurs

Outils du site


webdev:wordpress:custom_posts

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
webdev:wordpress:custom_posts [15/06/2017 17:56] – [Remove the slug from the custom post] dolowebdev:wordpress:custom_posts [13/08/2020 00:23] (Version actuelle) dolo
Ligne 1: Ligne 1:
 +====== Customs posts, etc ======
 +⇒ **Ces infos sont basées sur le plugin [[https://github.com/Bulko/bulkWPlugin|BulkWPlugin]]**
 +
 +  * [[https://codex.wordpress.org/Function_Reference/wp_editor|wp_editor()]] - génère un form de WYSIWYG
 +  * [[https://developer.wordpress.org/reference/functions/add_meta_box/|add_meta_box()]] - ajoute une meta box dans l'admin
 +  * [[https://codex.wordpress.org/Function_Reference/wp_handle_upload|wp_handle_upload()]] - [[http://stackoverflow.com/questions/3249666/wordpress-3-0-custom-post-type-with-upload#answer-3255828|Exemple stackoverflow]]
 +
 +  * https://jeremyhixon.com/tools/
 +
 +  * [[https://developer.wordpress.org/resource/dashicons/|Référence Dashicons]]
 +
 +==== Récupérer la valeur d'un champ meta : ====
 +[[https://developer.wordpress.org/reference/functions/get_post_meta/|get_post_meta()]]
 +
 +ou
 +
 +$post->nom_du_meta_key
 +==== Ajouter le meta box ====
 +<Code>
 + public function addMetaBox()
 + {
 + add_meta_box(
 + 'home-en-bref',
 + 'En bref',
 + array($this, 'fichePdfHtml'),
 + null,
 + 'normal',
 + 'default'
 + );
 + }
 +</Code>
 +
 +
 +==== Enlever le main content field ====
 +[[https://developer.wordpress.org/reference/functions/register_post_type/|Doc]]
 +
 +<Code:linenums>
 + $args = array(
 + 'labels' => $labels,
 + 'hierarchical' => false,
 + 'description' => __( 'Videos to translate', 'video' ),
 + //'supports' => array( 'editor', 'thumbnail', 'title' ),
 + 'supports' => array( 'thumbnail', 'title' ), // Remove 'editor' from supports
 + 'public' => true,
 + 'show_ui' => true,
 + 'show_in_menu' => true,
 + 'menu_position' => 20,
 + 'menu_icon' => 'dashicons-format-video',
 + 'show_in_nav_menus' => true,
 + 'publicly_queryable' => true,
 + 'exclude_from_search' => false,
 + 'has_archive' => true,
 + 'query_var' => true,
 + 'can_export' => true,
 + 'rewrite' => true,
 + 'capability_type' => 'post'
 + );
 + register_post_type( 'video', $args );
 +</Code>
 +
 +==== Ajouter une custom taxonomy ====
 +Classe plugin :
 +<Code>
 + public function custom_taxonomy()
 + {
 + $labels = array(
 + 'name'                       => _x( 'Catégories', 'Taxonomy General Name', 'text_domain' ),
 + 'singular_name'              => _x( 'Catégorie', 'Taxonomy Singular Name', 'text_domain' ),
 + 'menu_name'                  => __( 'Catégorie', 'text_domain' ),
 + 'all_items'                  => __( 'All Items', 'text_domain' ),
 + 'parent_item'                => __( 'Parent Item', 'text_domain' ),
 + 'parent_item_colon'          => __( 'Parent Item:', 'text_domain' ),
 + 'new_item_name'              => __( 'New Item Name', 'text_domain' ),
 + 'add_new_item'               => __( 'Add New Item', 'text_domain' ),
 + 'edit_item'                  => __( 'Edit Item', 'text_domain' ),
 + 'update_item'                => __( 'Update Item', 'text_domain' ),
 + 'view_item'                  => __( 'View Item', 'text_domain' ),
 + 'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
 + 'add_or_remove_items'        => __( 'Add or remove items', 'text_domain' ),
 + 'choose_from_most_used'      => __( 'Choose from the most used', 'text_domain' ),
 + 'popular_items'              => __( 'Popular Items', 'text_domain' ),
 + 'search_items'               => __( 'Search Items', 'text_domain' ),
 + 'not_found'                  => __( 'Not Found', 'text_domain' ),
 + 'no_terms'                   => __( 'No items', 'text_domain' ),
 + 'items_list'                 => __( 'Items list', 'text_domain' ),
 + 'items_list_navigation'      => __( 'Items list navigation', 'text_domain' ),
 + );
 + $args = array(
 + 'labels'                     => $labels,
 + 'hierarchical'               => true,
 + 'public'                     => true,
 + 'show_ui'                    => true,
 + 'show_admin_column'          => true,
 + 'show_in_nav_menus'          => true,
 + 'show_tagcloud'              => true,
 + );
 + register_taxonomy( 'categorie-communique', array( 'communique' ), $args );
 + }
 +
 + public function hook()
 + {
 + parent::hook();
 + add_action( 'init', array( $this, 'custom_taxonomy' ) );
 + }
 +</Code>
 +Pour appeller cette taxonomy : [[https://developer.wordpress.org/reference/functions/get_the_terms/|get_the_terms()]] ou [[https://codex.wordpress.org/Function_Reference/the_terms|the_terms()]]
 +
 +==== Ajouter un WYSIWYG ====
 +<Code>
 + <p>
 + <label for="encart_vert" style="font-weight: bold;"><?php _e( 'Encart affiché au milieu de la page d\'accueil', 'champ_supplmentaire' ); ?></label><br>
 + <?php wp_editor(
 + htmlspecialchars_decode( $this->getMeta( 'encart_vert' ) ),
 + "encart_vert",
 + array(
 + 'textarea_rows'=>12,
 + 'editor_class'=>'encart_vert')
 + );
 + ?>
 + </p>
 +</Code>
 +Sauvegarde du champ :
 +<Code>
 +public function saveMetaData( $post_id )
 +{
 + // ...
 + if ( isset( $_POST['encart_vert'] ) )
 + {
 + update_post_meta( $post_id, 'encart_vert', esc_attr( $_POST['encart_vert'] ) );
 + }
 +}
 +</Code>
 +Afficher correctement le champ :
 +<Code>
 +echo htmlspecialchars_decode($post->encart_vert);
 +</Code>
 +
 +==== Ajouter un champs texte classique ====
 +<Code>
 + <p>
 + <label for="phrase_intro">Texte affiché au-dessus du titre</label><br/>
 + <input type="text" name="phrase_intro" value="<?php echo $this->getMeta('phrase_intro'); ?>" style="width: 100%;"/>
 + </p>
 +</Code>
 +
 +<Code>
 + if( isset( $_POST['phrase_intro'] ) )
 + {
 + update_post_meta( $post_id, 'phrase_intro', esc_attr( $_POST['phrase_intro'] ) );
 + }
 +</Code>
 +
 +<code>
 + if( !empty($post->phrase_intro) )
 + {
 + echo '<div class="phrase-intro">' . $post->phrase_intro . '</div>';
 + }
 +</code>
 +==== Ajouter un champs image ====
 +=== Image unique ===
 +Code du champ simple :
 +<Code>
 + <p>
 + <label for="image-promotion" style="font-weight:bold;">Image de promotion</label><br/><br/>
 + <?php
 + if( !empty($this->getMeta( 'image-promotion' )) )
 + {
 + $img = wp_get_attachment_image_src( $this->getMeta( 'image-promotion' ), 'medium' );
 + echo '<img class="" src="' . $img[0] . '" alt="" width="' . $img[1] . '" height="' . $img[2] . '" style="max-width: 30%; vertical-align: bottom;" />';
 + } ?>
 + <input type="text" style="display: none;" name="image-promotion" id="image-promotion" class="image_id" value="<?php echo $this->getMeta( 'image-promotion' ); ?>">
 + <input type="button" id="upload-btn" class="button-secondary media_upload_single_bko" value="Choisir un fichier" style="vertical-align: bottom;">
 + </p>
 +</Code>
 +Sauvegarde du champ :
 +<Code>
 +public function saveMetaData( $post_id )
 +{
 + // ...
 + if ( isset( $_POST['image-promotion'] ) )
 + {
 + update_post_meta( $post_id, 'image-promotion', esc_attr( $_POST['image-promotion'] ) );
 + }
 +}
 +</Code>
 +
 +Afficher ce champ :
 +<Code>
 +$img = wp_get_attachment_image_src( get_post_meta( get_the_ID(), 'image-promotion', true ), 'large' );
 +echo '<img class="offre" src="' . $img[0] . '" alt="" width="' . $img[1] . '" height="' . $img[2] . '" />';
 +</Code>
 +=== Multi images ===
 +<Code>
 + <p>
 + <label for="encart_bas_image" style="font-weight: bold;">Image de fond de l'encart en bas de la page</label><br/>
 + <button class="display_button button-secondary">Ajouter une image</button>
 + <p class="model">
 + <label for="encart_bas_image">URL</label><br>
 + <input type="text" name="encart_bas_image[]" class="image_path_text" value=""><input type="button" id="upload-btn" class="button-secondary media_upload_bko" value="Choisir un fichier"><a class="delete_image_bko"> <span class="dashicons dashicons-no-alt bigger"></span> </a>
 + </p>
 +
 + <?php
 + $serialized_images = $this->getMeta('encart_bas_image');
 + $images = unserialize($serialized_images);
 + if(!empty( $images ) )
 + {
 + foreach ($images as $key => $image) {
 + ?>
 + <p class="image_slider">
 + <label for="encart_bas_image">URL</label><br>
 + <input type="text" name="encart_bas_image[]" class="image_path_text" value="<?php echo $image; ?>"><input type="button" id="upload-btn" class="button-secondary media_upload_bko" value="Choisir un fichier"><a class="delete_image_bko"> <span class="dashicons dashicons-no-alt bigger"></span> </a>
 + </p>
 + <?php
 + }
 + }
 + echo '</p>';
 +</Code>
 +Sauvegarde :
 +<Code>
 +public function saveMetaData( $post_id )
 +{
 + // ...
 + if( isset( $_POST['encart_bas_image'] ) )
 + {
 + foreach ($_POST['encart_bas_image'] as $key => $image) {
 + if($image == ''){
 + unset($_POST['encart_bas_image'][$key]);
 + }
 + }
 + $_POST['encart_bas_image'] = array_values($_POST['encart_bas_image']);
 + update_post_meta( $post_id, 'encart_bas_image', serialize( $_POST['encart_bas_image'] ) );
 + }
 +}
 +</Code>
 +Afficher ce code :
 +<Code>
 + $images = unserialize(get_post_meta( get_the_ID(), 'encart_bas_image', true ));
 + if(!empty( $images ))
 + {
 + echo ' style="background-image: url(\'' . $images[0] . '\');">';
 + }
 +</Code>
 +
 +---------
 +JS à ajouter à ce code :
 +<hidden><Code>
 +jQuery(function ($) {
 + //ADD MEDIA UPLOADER/SELECTOR
 + function upload_image(e, text_input, id_input = null)
 + {
 + // e.preventDefault();
 + var image = wp.media({
 + title: 'Choisir une image',
 + // mutiple: true if you want to upload multiple files at once
 + multiple: false
 + }).open()
 + .on('select', function(e){
 + // This will return the selected image from the Media Uploader, the result is an object
 + var uploaded_image = image.state().get('selection').first();
 + // We convert uploaded_image to a JSON object to make accessing it easier
 + // Output to the console uploaded_image
 + var image_url = uploaded_image.toJSON().url;
 +
 + // Let's assign the url value to the input field
 + if( text_input !== null )
 + {
 + $(text_input).val(image_url);
 + }
 +
 + if( id_input !== null )
 + {
 + $(id_input).val( uploaded_image.toJSON().id );
 + }
 + // window.aa_name_img_input[$(text_input).parent().index('.image_slider')] = image_url;
 + // console.log(window.aa_name_img_input);
 + });
 + };
 +
 + function delete_image(e, del){
 + del.parent().children('.image_path_text').val('');
 + del.parent().slideToggle();
 + }
 +
 + // protect user role ie fix :poop:
 + $('select#role option[value="administrator"]').remove();
 + $('select#role option[value=""]').remove();
 +
 + p = '<p class="image_slider"></p>';
 + // window.aa_name_img_input = [];
 + $('.model').css('display', 'none');
 + var model = $('.model').html();
 + $('.display_button').click(function(e)
 + {
 + e.preventDefault();
 + $(this).parent().append(p);
 + $(this).parent().children('p').last().append(model);
 + var upload = $(this).parent().children('p').last().children('.media_upload_bko');
 + var text_input = upload.prev('.image_path_text');
 + var del = $(this).parent().children('p').last().children('.delete_image_bko');
 + upload.on('click', function(){
 + upload_image(e, text_input);
 + });
 + del.on('click', function(){
 + delete_image(e, del);
 + });
 +
 + });
 +
 + $('.delete_image_bko').click( function(e)
 + {
 + delete_image(e, $(this));
 + });
 +
 + $('.media_upload_bko').click( function(e)
 + {
 + text_input = $(this).prev('.image_path_text');
 + upload_image(e, text_input);
 + });
 +
 + $('.media_upload_single_bko').click( function(e)
 + {
 + text_input = $(this).prev('.image_id');
 + upload_image(e, null, text_input);
 + });
 +});
 +
 +</Code></hidden>
 +
 +==== Afficher les champs customs sous conditions ====
 +=== Limiter à la page d'accueil ===
 +On peut mettre les conditions directement dans le hook **add_meta_boxes** si on fait remonter ses paramètres :
 +<Code>
 +add_action( 'add_meta_boxes', array( $this, 'addMetaBox' ), 10, 2 );
 +
 +public function addMetaBox($post_type, $post)
 +{
 + // On affiche la meta box que si la page est en homepage
 + if($post->ID == get_option('page_on_front'))
 + {
 + add_meta_box(
 + 'home-en-bref',
 + 'En bref',
 + array($this, 'homeCustomFields'),
 + 'page',
 + 'normal',
 + 'default'
 + );
 + }
 +}
 +</Code>
 +
 +Afficher seulement pour un champ en particulier :
 +<Code>
 +public function champHtml( $post )
 +{
 + // On affiche ces champs que si la page est en homepage
 + if($post->ID == get_option('page_on_front'))
 + {
 + // ...
 + }
 +}
 +</Code>
 +
 +Afficher suivant le modèle de page :
 +<code>
 +<?php
 + if( get_page_template_slug( $post->ID ) == 'page-2-colonnes.php' )
 + {
 + ?>
 + <p>
 + <label for="colonne_droite">Texte de la colonne de droite</label><br>
 + <?php wp_editor(
 + htmlspecialchars_decode( $this->getMeta( 'colonne_droite' ) ),
 + "colonne_droite",
 + array(
 + 'textarea_rows'=>12,
 + 'editor_class'=>'colonne_droite')
 + );
 + ?>
 + </p><?php
 + }
 +</code>
 +
 +==== Remove the slug from the custom post ====
 +[[https://stackoverflow.com/questions/12232715/how-can-i-remove-slug-in-custome-post-type-url#answer-32758129|Source]]
 +
 +<Code linenums>
 +public function parse_request( $query )
 +{
 + if ( ! $query->is_main_query() || ! isset( $query->query['page'] ) )
 + {
 + return;
 + }
 +
 + if ( ! empty( $query->query['name'] ) )
 + {
 + $query->set( 'post_type', array( 'post', 'produits', 'page' ) );
 + }
 +}
 +
 +public function hook()
 +{
 + parent::hook();
 + add_action( 'pre_get_posts', array($this, 'parse_request') );
 +}
 +
 +
 +////////////////////////////////////////////////////////////
 +
 +
 +register_post_type( 'dummy', array(
 + //other custom posttype definitions 
 + 'rewrite' => array(
 + 'slug' => '/',
 + // 'with_front' => false,
 + ),
 +) );
 +</Code>
 +
 +__**Then re-register the permalink option to make it effective**__.
 +
 +
 +[[https://wordpress.stackexchange.com/questions/203951/remove-slug-from-custom-post-type-post-urls#answer-204210|Source of the answer]]