WordPress: creare una funzione per le opzioni del tema

WordPress: creare una funzione per le opzioni del tema

Sicuramente avrete notato che molti temi non utilizzano direttamente la funzione di WordPress get_option() per reperire le varie opzioni impostate dall'utente ma preferiscono usare una loro funzione personalizzata per questo scopo. Vediamo come creare questa funzione per i nostri temi.

Aggiungete il seguente codice al file functions.php, ovviamente modificando il nome della funzione:


function my_theme_option($key) {

	global $settings;
	
	$option = get_option($settings);
	
	if(isset($option[$key])) {
		return $option[$key];
	} else { 
		return false;
		
	}
}

Ecco un esempio pratico di come utilizzare la nostra funzione nel tema (home.php):

[php htmlscript="true"] <div id="home-category"> <?php $home_cat = new WP_Query("cat=" . my_theme_option('home_cat'). "&showposts=1"); while($home_cat->have_posts()) : $home_cat->the_post();?> <h1><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h1> <p><?php the_excerpt();?></p> <?php endwhile; ?> <?php wp_reset_postdata(); ?> </div>
Torna su