WordPress: usare i meta box e i campi meta

I meta box di WordPress sono uno strumento molto utile che può essere aggiunto ad ogni post o pagina. Il loro scopo è semplice: essi aggiungono dei campi extra con cui contrassegnare il post o la pagina. In questo articolo ne vedremo un esempio pratico.

Aggiungere i meta box

Supponiamo che il nostro cliente ci chieda di poter selezionare manualmente un post o gruppo di post da inserire nella home page. Definiremo pertanto un campo chiamato test con cui contrassegnare i nostri post o le nostre pagine.

Inseriremo il seguente codice nel file functions.php:

[php htmlscript="true"] <?php add_action('admin_init', 'test_init'); add_action('save_post', 'save_test'); function test_init(){ add_meta_box("test", "Test", "test_meta", "post", "normal", "high"); add_meta_box("test", "Test", "test_meta", "page", "normal", "high"); } function test_meta() { global $post; $custom = get_post_custom($post->ID); $test = $custom["test"][0]; ?> <div class="inside"> <table class="form-table"> <tr> <th><label for="test">Usare nella home page?</label></th> <td><input type="checkbox" name="test" value="1" <?php if($test == 1) { echo "checked='checked'";} ?></td> </tr> </table> </div> <?php } function save_test(){ if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return $post_id; global $post; if($post->post_type == "post" || $post->post_type == "page") { update_post_meta($post->ID, "test", $_POST["test"]); } } ?>

Il codice usa due azioni di WordPress: admin_init e save_post. Alla prima viene associata la creazione dei due meta box, uno per i post e l'altro per le pagine.

La seconda, invece, viene usata per salvare il valore del campo in uso, ossia test. Come potete notare, a ciascuna azione è associata una funzione specifica.

Usare i meta box

Possiamo usare la classe WP_Query per reperire i post o le pagine aventi un campo specifico:


$test = new WP_Query(array('meta_key' => 'test', 'meta_value' => 1, 'posts_per_page' => 1));
	 					
if($test->have_posts()) {

	while($test->have_posts()) {
	
		$test->the_post();
		
		
		//... continua
	
	
	}


}

Vengono usati in questo caso i parametri meta_key e meta_value della classe WP_Query per reperire il campo richiesto.

Torna su