Nessun risultato. Prova con un altro termine.
Guide
Notizie
Software
Tutorial

Migliorare WordPress senza plugin

Tanti snippet di codice da usare per migliorare WordPress senza ricorrere a plugin esterni
Tanti snippet di codice da usare per migliorare WordPress senza ricorrere a plugin esterni
Link copiato negli appunti

In questo articolo vedremo come implementare soluzioni per i nostri siti in WordPress ottenute senza l'ausilio di plugin. Lo scopo è quello di dimostrare come non sempre un plugin sia l'unica soluzione possibile.

Creare un listato di file

Figura 1. Listato di file
Listato di file

Il seguente codice utilizza gli iteratori di directory di PHP per estrarre il percorso dei file da una directory a scelta e restituire degli URL assoluti. Per utilizzare lo snippet basterà inserire il blocco di codice nel file functions.php del tema che utilizzate su WordPress:

Listato di file

function search_dir($dir){
  $pages = array();
  foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $file) {
    if ($file->isFile() && $file->isReadable()) {
      if(preg_match('/.zip$/', $file)) {
        $zip = $file->getPathname();
        $pages[] = $zip;
      }
      if(preg_match('/.pdf$/', $file)) {
      	  	$pdf_doc = $file->getPathname();
      	  	$pages[] = $pdf_doc;
      }
    }
  }
  return $pages;
}
function sort_by_date($a, $b){
     $time1 = filectime($a);
     $time2 = filectime($b);
     return $time1 < $time2;
}
function directory_listing($atts) {
	extract( shortcode_atts( array(
		'dir' => ''
	), $atts ) );
	$files = search_dir($_SERVER['DOCUMENT_ROOT'] . '/' . $dir);
	usort($files, 'sort_by_date');
	$html = '<ul>' . "n";
	foreach($files as $file) {
		$uri = substr_replace($file, '', 0, strlen($_SERVER['DOCUMENT_ROOT']));
		$full_url = 'http://' . $_SERVER['HTTP_HOST'] . $uri;
        $html .= '<li><a href="' . $full_url . '">' . $file . '</a></li>' . "n";
	}
	$html .= '</ul>' . "n";
	return $html;
}
add_shortcode('directory', 'directory_listing');

Quindi possiamo usare il seguente shortcode:

Utilizzo del listato di file

[directory dir="documenti"]

Le due espressioni regolari usate, ossia:

/.zip$/
/.pdf$/

selezionano file ZIP e PDF. È sufficiente modificare queste espressioni regolari per selezionare altri tipi di file.

Impostare il meta tag description

La seguente funzione utilizza dei costrutti if e i tag condizionali di WordPress (es. is_home, is_single etc.) in base ai quali verifica in quale sezione del sito ci troviamo ed imposta il meta tag description sul valore più appropriato. Nel functions.php del tema va inserito il seguente snippet di codice:

function set_meta_description() {
		if(is_home()) {
			bloginfo('description');
		} else if(is_single()) {
			$excerpt = strip_tags(get_the_excerpt());
			echo $excerpt;
		} else if(is_page()) {
			the_title();	
		} else if(is_category()) {
			$cat_desc = category_description();
			if($cat_desc != '') {
				echo $cat_desc;
			} else {
				echo single_cat_title();
			}
		} else {
			bloginfo('description');
		}
}

Andrà modificato anche il file header.php del tema, in questo modo:

<meta name="description" content="<?php set_meta_description();?>"/>

Visualizzare i post da una categoria casuale

La seguente funzione utilizza la funzione get_categories() per estrarre un valore casuale dall'array di categorie restituito e quindi usare tale valore per selezionare una categoria casuale e i suoi post.

function get_posts_from_random_category() {
	$cat = '';
	$html = '';
	$categories = get_categories();
	$index = mt_rand(0, count($categories));
	$cat = $categories[$index]->term_id;
	$loop = new WP_Query(array('cat' => $cat, 'posts_per_page' => 3));
	$html .= '<div id="random-posts">';
	if($loop->have_posts()) {
		while($loop->have_posts()) {
			$loop->the_post();
			$html .= '<div class="random-post">';
			$html .= '<h2><a href="' . get_permalink() . '">' . get_the_title() . '</a></h2>';
			$html .= '<p>' . get_the_excerpt() . '</p>';
			$html .= '</div>';
		}
	}
	$html .= '</div>';
	return $html;
}

Quindi potete inserire la funzione appena definita nel vostro tema:

<?php echo get_posts_from_random_category(); ?>

Mostrare i post programmati

La seguente funzione utilizza la classe WP_Query per selezionare i post il cui status sia future. Andrà inserito nel file functions.php il seguente codice:

function show_scheduled_posts() {
	$query = new WP_Query(array('showposts'=>3, 'post_status'=>'future', order=>'ASC'));
	$html = '';
	if($query->have_posts()) {
	        $html .= '<div id="upcoming-posts">';
		$html .= '<ul>';
		while($query->have_posts()) {
			$query->the_post();
			$html .= '<li><strong>' . get_the_title() . '</strong><span>' .
					  get_the_date() . '</span></li>';
		}
		$html .= '</ul></div>';
	} else {
		$html .= '<p>Nessun articolo programmato.</p>';
	}
	return $html;	
}
add_shortcode('scheduled', 'show_scheduled_posts');

Potete quindi usare lo shortcode [scheduled] per richiamare in frontend, per esempio in un widget, i post futuri.

Generare un menu breadcrumb

La seguente funzione esegue dei blocchi if nelle varie sezioni del sito ed in base alla categoria o post genera un menu breadcrumb. Inserite il seguente codice nel functions.php del vostro tema:

function create_breadcrumbs() {
  $delimiter = '/';
  $home = 'Home';
  $before = '<span class="current">';
  $after = '</span>';
  if ( !is_home() && !is_front_page() || is_paged() ) {
    echo '<div id="breadcrumbs">';
    global $post;
    $homeLink = get_bloginfo('url');
    echo '<a href="' . $homeLink . '">' . $home . '</a> ' . $delimiter . ' ';
    if ( is_category() ) {
      global $wp_query;
      $cat_obj = $wp_query->get_queried_object();
      $thisCat = $cat_obj->term_id;
      $thisCat = get_category($thisCat);
      $parentCat = get_category($thisCat->parent);
      if ($thisCat->parent != 0) echo(get_category_parents($parentCat, TRUE, ' ' . $delimiter . ' '));
      echo $before . single_cat_title('', false) . $after;
    } elseif ( is_day() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo '<a href="' . get_month_link(get_the_time('Y'),get_the_time('m')) . '">' . get_the_time('F') . '</a> ' . $delimiter . ' ';
      echo $before . get_the_time('d') . $after;
    } elseif ( is_month() ) {
      echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
      echo $before . get_the_time('F') . $after;
    } elseif ( is_year() ) {
      echo $before . get_the_time('Y') . $after;
    } elseif ( is_single() && !is_attachment() ) {
      if ( get_post_type() != 'post' ) {
        $post_type = get_post_type_object(get_post_type());
        $slug = $post_type->rewrite;
        echo '<a href="' . $homeLink . '/' . $slug['slug'] . '/">' . $post_type->labels->singular_name . '</a> ' . $delimiter . ' ';
        echo $before . get_the_title() . $after;
      } else {
        $cat = get_the_category(); $cat = $cat[0];
        echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
        echo $before . get_the_title() . $after;
      }
    } elseif ( !is_single() && !is_page() && get_post_type() != 'post' && !is_404() ) {
      $post_type = get_post_type_object(get_post_type());
      echo $before . $post_type->labels->singular_name . $after;
    } elseif ( is_attachment() ) {
      $parent = get_post($post->post_parent);
      $cat = get_the_category($parent->ID); $cat = $cat[0];
      echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
      echo '<a href="' . get_permalink($parent) . '">' . $parent->post_title . '</a> ' . $delimiter . ' ';
      echo $before . get_the_title() . $after;
    } elseif ( is_page() && !$post->post_parent ) {
      echo $before . get_the_title() . $after;
    } elseif ( is_page() && $post->post_parent ) {
      $parent_id  = $post->post_parent;
      $breadcrumbs = array();
      while ($parent_id) {
        $page = get_page($parent_id);
        $breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
        $parent_id  = $page->post_parent;
      }
      $breadcrumbs = array_reverse($breadcrumbs);
      foreach ($breadcrumbs as $crumb) echo $crumb . ' ' . $delimiter . ' ';
      echo $before . get_the_title() . $after;
    } elseif ( is_search() ) {
      echo $before . get_search_query() . $after;
    } elseif ( is_tag() ) {
      echo $before . single_tag_title('', false) . $after;
    } elseif ( is_author() ) {
       global $author;
      $userdata = get_userdata($author);
      echo $before . $userdata->display_name . $after;
    } elseif ( is_404() ) {
      echo $before . 'Error 404' . $after;
    }
    if ( get_query_var('paged') ) {
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
      echo __('Page') . ' ' . get_query_var('paged');
      if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
    }
    echo '</div>';
  }
}

Quindi potete inserire la funzione create_breadcrumbs() nel vostro tema dove volete che compaia il menu:

Funzione breadcrumb

<?php create_breadcrumbs(); ?>

Mostrare i post recenti con il numero di commenti

Lo snippet utilizza le funzioni per la gestione del database di WordPress (come l'oggetto wpdb) per mostrare i post recenti ed il numero di commenti ad essi associati. Nel functions.php andrà inserito:

function show_recent_articles() {
	global $wpdb;
	$args = array(
		'posts_per_page' => 30,
		'orderby' => 'date'
               );
	$loop = new WP_Query($args);
        $html .= '<div id="recent-posts"><h3>Recent posts</h3>';
        $html .= '<ul>';
        while($loop->have_posts()) {
		$loop->the_post();
		$id = get_the_ID();
		$comments = $wpdb->get_row("SELECT comment_count as count FROM $wpdb->posts WHERE ID = '$id'");
		$comments_no = $comments->count;
          	$html .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a><small>' . get_the_date() . '</small><div>' .
			  $comments_no . ' comments</div></li>';
        }
	$html .= '</ul></div>';
	echo $html;
}

Quindi potete aggiungere la funzione show_recent_articles() al vostro tema:

<?php show_recent_articles();?>

Creare la paginazione dei post

La seguente funzione sfrutta l'oggetto $wp_query per ottenere il numero di post visualizzabile per ogni pagina. In base a quello genera i vari link per la paginazione.

function create_pagination($pages = '', $range = 2) {
	$show_items = ($range * 2) + 1;
	global $paged;
	if(empty($paged)) {
		$paged = 1;
	}
	if($pages == '') {
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         if(!$pages) {
             $pages = 1;
         }
     } 
     if(1 != $pages) {
         echo '<div id="pagination">';
         if($paged > 2 && $paged > $range+1 && $show_items < $pages) echo "<a href='".get_pagenum_link(1)."'>«</a>";
         if($paged > 1 && $show_items < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>‹</a>";
         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? '<strong>'.$i."</strong>":"<a href='".get_pagenum_link($i)."' class="inactive">".$i."</a>";
             }
         }
         if ($paged < $pages && $show_items < $pages) echo "<a href='".get_pagenum_link($paged + 1)."'>›</a>";
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $show_items < $pages) echo "<a href='".get_pagenum_link($pages)."'>»</a>";
         echo "</div>n";
     }
}

Quindi usate la funzione create_pagination() nel vostro tema:

<?php create_pagination(); ?>

Mostrare il numero di post pubblicati

Con il codice che vedrete, viene utilizzata la funzione di WordPress wp_count_posts() per selezionare il numero di post pubblicati.

function count_posts() {
    $count_posts = wp_count_posts();
    $published_posts = $count_posts->publish;
    return '<p class="posts-no"><span>' . $published_posts . ' articoli pubblicati' . '</span></p>';
}

Quindi inserite la funzione count_posts() nel vostro tema:

<?php echo count_posts(); ?>

Inserire l'ultimo tweet nell'header

La seguente funzione interroga il feed XML del vostro status Twitter ed utilizza l'estensione PHP SimpleXML per effettuarne il parsing.

Figura 3. Tweet in WordPress
Tweet in WordPress

Nel file functions.php andrà inserito:

function get_latest_tweet($twitter_user = 'gabromanato') {
	$html = '';
	$html .= '<div id="latest-tweet">';
	$url = "http://twitter.com/statuses/user_timeline/$twitter_user.xml?count=1";
	if(file_get_contents($url)) {
		$xml = new SimpleXMLElement(file_get_contents($url));
		$status = $xml->status->text;
		$time = nice_time(strtotime($xml->status->created_at));
		$tweet = preg_replace('/http://(.*?)/[^ ]*/', '<a href=""></a>', $status);
		$html .= '<div id="tweet">' . $tweet . '</div>';
		$html .= '<div id="tweet-time">' . $time . '</div>';
	} else {
		$html .= '<div id="tweet">Twitter non risponde.</div>';
	}
	$html .= '</div>';
	return $html;
}
function nice_time($time) {
  $delta = time() - $time;
  if ($delta < 60) {
    return 'meno di 1 minuto fa.';
  } else if ($delta < 120) {
    return 'circa 1 minuto fa.';
  } else if ($delta < (45 * 60)) {
    return floor($delta / 60) . ' minuti fa.';
  } else if ($delta < (90 * 60)) {
    return 'circa 1 ora fa.';
  } else if ($delta < (24 * 60 * 60)) {
    return 'circa ' . floor($delta / 3600) . ' ore fa.';
  } else if ($delta < (48 * 60 * 60)) {
    return '1 giorno fa.';
  } else {
    return floor($delta / 86400) . ' giorni fa.';
  }
}

Quindi usate la funzione get_latest_tweet() nel vostro file header.php, ovviamente inserendo come parametro $twitter_user il vostro nome utente su Twitter:

Usare il codice per importare l'ultimo tweet

	<div id="header">
	
		<?php echo get_latest_tweet('tuonomeutente'); ?>
	
	</div>

Visualizzare il numero di fan della nostra pagina di Facebook

La seguente funzione interroga le API di Facebook ed utilizza l'estensione PHP SimpleXML per effettuare il parsing della risposta.

function display_facebook_fans($page) {
	$page_id = $page;
	$xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("errore");
	$fans = $xml->page->fan_count;
	echo $fans;
}

$page è l'ID della vostra pagina di Facebook. Nel mio caso è gabrieleromanatopage:

<p>Fan su Facebook: <?php display_facebook_fans('gabrieleromanatopage'); ?></p>

Ti consigliamo anche