Table des matières

Customs posts, etc

Ces infos sont basées sur le plugin BulkWPlugin

Récupérer la valeur d'un champ meta :

get_post_meta()

ou

$post→nom_du_meta_key

Ajouter le meta box

	public function addMetaBox()
	{
		add_meta_box(
			'home-en-bref',
			'En bref',
			array($this, 'fichePdfHtml'),
			null,
			'normal',
			'default'
		);
	}

Enlever le main content field

Doc

		$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 );

Ajouter une custom taxonomy

Classe plugin :

	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' ) );
	}

Pour appeller cette taxonomy : get_the_terms() ou the_terms()

Ajouter un WYSIWYG

			<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>

Sauvegarde du champ :

public function saveMetaData( $post_id )
{
	// ...
	if ( isset( $_POST['encart_vert'] ) )
	{
		update_post_meta( $post_id, 'encart_vert', esc_attr( $_POST['encart_vert'] ) );
	}
}

Afficher correctement le champ :

echo htmlspecialchars_decode($post->encart_vert);

Ajouter un champs texte classique

		<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>
		if( isset( $_POST['phrase_intro'] ) )
		{
			update_post_meta( $post_id, 'phrase_intro', esc_attr( $_POST['phrase_intro'] ) );
		}
		if( !empty($post->phrase_intro) )
		{
			echo '<div class="phrase-intro">' . $post->phrase_intro . '</div>';
		}

Ajouter un champs image

Image unique

Code du champ simple :

			<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>

Sauvegarde du champ :

public function saveMetaData( $post_id )
{
	// ...
	if ( isset( $_POST['image-promotion'] ) )
	{
		update_post_meta( $post_id, 'image-promotion', esc_attr( $_POST['image-promotion'] ) );
	}
}

Afficher ce champ :

$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] . '" />';

Multi images

			<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>';

Sauvegarde :

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'] ) );
	}
}

Afficher ce code :

	$images = unserialize(get_post_meta( get_the_ID(), 'encart_bas_image', true ));
	if(!empty( $images ))
	{
		echo ' style="background-image: url(\'' . $images[0] . '\');">';
	}

JS à ajouter à ce code :

Cliquez pour afficher ⇲

Cliquez pour masquer ⇱

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);
	});
});

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 :

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'
		);
	}
}

Afficher seulement pour un champ en particulier :

public function champHtml( $post )
{
	// On affiche ces champs que si la page est en homepage
	if($post->ID == get_option('page_on_front'))
	{
		// ...
	}
}

Afficher suivant le modèle de page :

<?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
		}

Remove the slug from the custom post

Source

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,
	),
) );

Then re-register the permalink option to make it effective.

Source of the answer