Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
Coppa WPB
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

Come visualizzare la data di oggi in WordPress (2 semplici metodi)

Nota editoriale: guadagniamo una commissione dai link dei partner su WPBeginner. Le commissioni non influenzano le opinioni o le valutazioni dei nostri redattori. Per saperne di più su Processo editoriale.

Volete visualizzare la data di oggi in WordPress?

Molti siti web di notizie, riviste online e blog con aggiornamenti frequenti possono voler visualizzare la data e l’ora corrente. In questo modo gli utenti possono farsi un’idea della data attuale e di quanto tempo fa è stato pubblicato il contenuto.

In questo articolo vi mostreremo come visualizzare facilmente la data odierna o l’ora corrente sul vostro sito web WordPress.

Displaying current date and time in WordPress

Perché visualizzare la data di oggi in WordPress?

Molti siti web di notizie visualizzano la data corrente nella sezione header dei loro siti, in particolare quelli più piccoli che pubblicano le loro storie principali su base giornaliera.

A news website showing current date in their website header

Questo assicura agli utenti che stanno visualizzando l’ultima edizione dell’edizione online della pubblicazione. Si tratta di un’utile scelta stilistica che molti siti web utilizzano ancora nonostante l’aggiornamento delle loro home page più volte al giorno.

Allo stesso modo, anche i giornali online e i blogger hanno adottato questo stile. In questo modo si assicura agli utenti che stanno visualizzando le ultime voci di un blog.

Esistono altri scenari d’uso in cui è sufficiente mostrare la data e l’ora corrente.

Ad esempio, se la vostra live chat funziona a orari specifici e volete mostrare ai clienti che ora è nella vostra posizione geografica. Oppure, se state conducendo una campagna con un conto alla rovescia e volete mostrare la data attuale per creare un effetto FOMO più forte.

Detto questo, vediamo come visualizzare facilmente la data, il giorno o l’ora corrente sul vostro sito web WordPress. Copriremo due metodi e potete usare i collegamenti rapidi qui sotto per passare a quello che volete usare:

Metodo 1: visualizzazione della data odierna mediante l’aggiunta di codice a un template file

WordPress non dispone di un widget o di un blocco predefinito per visualizzare la data o l’ora corrente.

Tuttavia, è possibile visualizzare la data o l’ora corrente utilizzando del codice molto semplice.

È possibile aggiungere questo semplice codice ai template del tema di WordPress dove si desidera visualizzare l’ora:

<?php echo date(get_option('date_format')); ?>

Questo codice stampa semplicemente la data corrente utilizzando il formato della data impostato nelle impostazioni di WordPress. È possibile modificare il formato della data visitando la pagina Impostazioni ” Generali”.

Time format settings in WordPress

È anche possibile utilizzare i propri tag di formattazione per stampare la data in qualsiasi altro formato. Ad esempio, utilizzando il codice seguente, è possibile stampare la data nel formato mese, giorno e anno.

<?php echo date('F j, Y'); ?>

Ecco come appariva sul nostro sito web demo.

Date and time

Questo metodo consente di aggiungere direttamente il codice ai file del tema di WordPress, ma non è molto flessibile. E se voleste visualizzare la data e l’ora corrente all’interno di un articolo, di una pagina o di un widget della barra laterale di WordPress?

Il metodo successivo consente di add-on la data e l’ora in qualsiasi punto del sito.

Metodo 2: Visualizzare la data di oggi ovunque utilizzando uno shortcode (consigliato)

Per questo metodo, creeremo uno shortcode e lo utilizzeremo per visualizzare la data e l’ora in qualsiasi punto del nostro sito web WordPress.

È possibile aggiungere il seguente codice al file functions.php del tema o utilizzando un plugin di snippet di codice personalizzato come WPCode (consigliato):

function wpb_date_today( $atts, $content = null ) {
	$atts = shortcode_atts( array(
		'format' => '',
	), $atts );

	$date_time = '';

	if ( $atts['format'] == '' ) {
		$date_time .= date( get_option( 'date_format' ) );
	} else {
		$date_time .= date( $atts['format'] );
	}

	return $date_time;
}

add_shortcode( 'date-today', 'wpb_date_today' );

Questo codice crea semplicemente uno shortcode che visualizza la data corrente. È possibile utilizzarlo aggiungendo questo shortcode in qualsiasi punto del sito:

[data-oggi]

Per impostazione predefinita, lo shortcode visualizza la data nel formato predefinito nelle impostazioni di WordPress.

È anche possibile utilizzare il proprio formato di data modificando lo shortcode in questo modo:

[date-today format='F j, Y']

Sul vostro sito web dovrebbe avere un aspetto simile a questo.

Date preview

Guide di esperti sulla visualizzazione delle date in WordPress

Ora che sapete come visualizzare la data di oggi in WordPress, potreste voler vedere altre guide relative alla visualizzazione delle date in WordPress:

Speriamo che questo articolo vi abbia aiutato a capire come visualizzare facilmente la data di oggi in WordPress. Potreste anche voler consultare la nostra guida su come add-on le previsioni del tempo in WordPress o le nostre scelte di esperti per i migliori plugin di quiz per WordPress.

Se questo articolo vi è piaciuto, iscrivetevi al nostro canale YouTube per le esercitazioni video su WordPress. Potete trovarci anche su Twitter e Facebook.

Divulgazione: I nostri contenuti sono sostenuti dai lettori. Ciò significa che se cliccate su alcuni dei nostri link, potremmo guadagnare una commissione. Vedi come WPBeginner è finanziato , perché è importante e come puoi sostenerci. Ecco il nostro processo editoriale .

Avatar

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

Il kit di strumenti WordPress definitivo

Ottenete l'accesso gratuito al nostro kit di strumenti - una raccolta di prodotti e risorse relative a WordPress che ogni professionista dovrebbe avere!

Reader Interactions

37 commentiLascia una risposta

  1. Syed Balkhi says

    Hey WPBeginner readers,
    Did you know you can win exciting prizes by commenting on WPBeginner?
    Every month, our top blog commenters will win HUGE rewards, including premium WordPress plugin licenses and cash prizes.
    You can get more details about the contest from here.
    Start sharing your thoughts below to stand a chance to win!

  2. Dennis Muthomi says

    hi, I got a question for the time display:- what if my website has visitors from different time zones? will the date and time displayed be adjusted to their local time, or will it always show the time based on the website’s settings?

  3. Mrteesurez says

    Thanks for sharing.
    The time is not showing, only the date is showed. I want to show both date and time beside each other on the top for all visitorsb to see including the admins.

  4. Bert Hennephof says

    Code doesn’t work anymore after upgrade from PHP 7.4 to PHP 8.2
    WPCode indicates error in line:
    if ($atts[‘format’] == ”) {

    • WPBeginner Support says

      From testing the snippet on our end it currently is working in php 8.2, it would depend on the specific error message you are seeing on the line.

      Admin

  5. Ihtisham Z says

    Thank you for the great article.

    Just wanted to note here that, if the format attribute is not provided by the user then the shortcode will fail resulting in a critical error (parsing the attribute as string) and breaking the page. So, we need to convert the string to an array.

    function wpb_date_today($atts, $content = null) {
    if ( ! is_array( $atts ) ) {
    $atts = [];
    }

    // rest of the code…
    }

    • Chris Colotti says

      Thanks for the code update!!! Snippet had been working for some time then broke as you indicated..

  6. Generosus says

    Useful Tip:

    Method 2 (listed above) yields a date output in UTC format. To change the output to Local Time format, replace “date” with “wp_date” (2 places).

    It would be great to make a notation in your above instructions.

    You’re welcome :)

  7. Kathy says

    I really wanted to use this, however, after adding it to my functions file, I get this:
    Warning: Illegal string offset ‘format’ in /XXXXXXXXXX/functions.php

    It showed the date, however, the warning showed up too.

    • WPBeginner Support says

      Thank you for letting us know, we will look into this and for the time being the second shortcode with the format specified will avoid that warning.

      Admin

    • WPBeginner Support says

      For adding the date as numbers if you are using the echo date method, you would change F j, Y to m/d/Y

      Admin

  8. Rebekah says

    Is it possible to display a moving date? For instance, today’s date plus 7 days? I’d like to have something on my site that always displays the date one week from today.

  9. Henry says

    Adding this php code in the header file is OK but how can I control where I want to appear my date on the page?

  10. Jon says

    Or with Javascript:

    var dateToday = new Date(); var yearToday = dateToday.getFullYear(); document.write(yearToday);

  11. Clare says

    I’m beginning to discover that you can do anything with WP if you just take the time out to learn how – and most of it is so simple. 2011 is the year to ditch plugins and take the weight off my site!

    • Editorial Staff says

      We mentioned two solutions. One where you can use the server’s setting, or two where you can use WordPress setting. If you have a third solution, then please share it with us rather than saying that we are wrong because both solutions above work.

      Admin

Lascia una risposta

Grazie per aver scelto di lasciare un commento. Tenga presente che tutti i commenti sono moderati in base alle nostre politica dei commenti e il suo indirizzo e-mail NON sarà pubblicato. Si prega di NON utilizzare parole chiave nel campo del nome. Avremo una conversazione personale e significativa.