I posted a comment on Dates on Blog Posts - Should You Have Them? last week over at Problogger.Net on how easy it would be to implement code to a theme which would allow a user to show or hide content based on the date or age of a post. Аз публикуван коментар за датите, на блога пощи - Трябва ли ги? Миналата седмица над Problogger.Net за това как най-лесно ще бъде да изпълнява код, за да изберете тема, която да позволи на потребителя да показване или скриване на съдържанието на базата на датата или възраст на пост. I’ve since gotten a few emails about this in particular and was going to share this with some of these tricks I had mentioned when I did the redesign of this site last week . Аз бях тъй като придобих малко имейли за това по-специално и щеше да споделя това с някои от тези трикове имах споменати когато го направиха дизайн на този сайт миналата седмица.

Straight from Problogger.net , here was the initial inquiry: Прави от Problogger.net, тук беше първоначалното разследване:

Dates on Recent Posts But Not on Older Ones - I saw one blogger do this last year (I’m afraid I don’t remember who it was). Дати за нова Постове Но не по-стари такива - Видях един часа Blogger направите това през миналата година (Опасявам се, че аз не помня кой беше). They had hacked WordPress so that dates appeared on recent posts (within the last 3 months) but anything older than that did not have time stamps either on the post or comments. Те са опростен УърдПрес така, че датите се яви на последните постове (в рамките на последните 3 месеца), но нищо по-големи, отколкото, че не са имали време, печати или по пощата или коментари. This meant that the blogger benefited from new posts looking new and took the potential distraction of old posts away from readers. Това означаваше, че Blogger възползвали от новите постове търсят нови и взех потенциал разсейване на старите постове от читателите. I don’t know exactly how the blogger did it but presume they set up a rule that looked at the date of authorship and then determined whether the date would be displayed or not. Аз не знам точно как го е направил Blogger, но по презумция те създават правилото, че погледна към датата на авторство и след това определя дали датата ще бъде показана или не.

In short, to do this you’ll be modifying your theme (/wp-content/themes/YOURTHEME/ index.php and/or single.php) rather then the core wordpress code. Накратко, за да направите това ще ви бъде модификация тема (/ wp-content/themes/YOURTHEME / index.php и / или single.php), а след това ядрото WordPress кодекс. Also I’m using wordpress 2.6 but this should work on anything wordpress 2.0 or later for sure. Също така съм използвайки WordPress 2,6, но това трябва да работят по нещо WordPress 2,0 или късно със сигурност. Anything lower it might work but you might need to redefine $postdate with whatever the_date() function was back then. Нещо по-ниски, че могат да работят, но може да се наложи да предефинират $ postdate с каквото the_date () функцията е била тогава. (It may very well be the same). (Той може много добре да са същите). Other then that, its good old PHP that handles it. Други след това, че неговите добри стари PHP, който обработва него.

  1. <?php
  2. //File: /wp-content/themes/YOURTHEME/ index.php and/or single.php
  3. //FIND:
  4. if ( have_posts ( ) ) : while ( have_posts ( ) ) : the_post ( ) ;
  5. //ADD UNDER:
  6. $twomonthsago = date ( "Ymd" , mktime ( 0 , 0 , 0 , date ( "m" ) -2 , date ( "d" ) , date ( "Y" ) ) ) ;
  7. $twentydaysago = date ( "Ymd" , mktime ( 0 , 0 , 0 , date ( "m" ) , date ( "d" ) -20 , date ( "Y" ) ) ) ;
  8. $currentdate = date ( "Ymd" , mktime ( 0 , 0 , 0 , date ( "m" ) , date ( "d" ) , date ( "Y" ) ) ) ;
  9. $postdate = the_date ( ‘Ymd’ , , , false ) ;
  10. ?>
  11. //ADD WHERE APPROPRIATE
  12. <?php
  13. if ( $postdate > $twentydaysago ) {
  14. echo $postdate ;
  15. ?>
  16. //Insert HTML code here for data you want to show if the post is newer (within 20 days old of posting)
  17. <?php } ?>
  18. //notice the greater than/less than sign flipped
  19. <?php
  20. if ( $postdate < $twentydaysago ) {
  21. echo $postdate ;
  22. ?>
  23. //Insert HTML code here for data you want to show older than 20 days ago.
  24. <?php } else { ?>
  25. //Insert HTML code here for data that is newer than 20 days.
  26. <?php } ?>

This code must be placed within the loop. Този код трябва да бъдат поставени в отклонение. By that I mean, it needs to be within that if (have_posts())… bit as shown in the code. До тази искам да кажа, то трябва да бъде в рамките на този когато (have_posts ()) ... малко, както е показано в кода. From there we’re grabbing the date using the_date(). От там ние сме grabbing датата, използвайки the_date (). You don’t have to use a separate variable for this, but I find it easier because I reference that variable more than once in the code. Не е нужно да се използва отделна променлива за това, но аз го намерите лесно, защото препратка променлива, че повече от един път в кода.

Some Uses For Showing & Hiding Content Някои употреби за показване и скриване на съдържанието
Among the uses that users have for this kind of implementation: Сред употреби, които потребителите имат за този вид институция:

  • AdSense or other Ads - Showing or hiding Ads on pages only after a certain date. AdSense или други реклами - показване или скриване на реклами на страниците, само след определена дата. Readers that keep up with your blog and look at all your new posts right away will appreciate this. Читателите, които водят до блога си и виж всички свои нови постове веднага ще оценят това. They are also your most loyal readers Те също са най-лоялни читатели
  • Social media tags - I’m doing this right now on this site. Социални медии марки - Аз съм правите това точно сега на този сайт. If the post is older than 20 days, I have it set to display social bookmarking links at the bottom of the post. Ако този пост е по-стар от 20 дни, имам го зададе да показва социалното Маркиране на връзките в дъното на пощата. If its newer, the bar displays at the top. Ако неговите по-нови, на бара показва най-отгоре.
  • Contests - If you have different content you want to display before or after a contest, you can use this method to automate the content switch for you. Конкурси - Ако имат различно съдържание, което искате да покажете пред или след конкурси, можете да използвате този метод, който да автоматизира съдържанието превключване за вас. For example. За пример. Before the contest you could wrap in your form code. Преди конкурса може да опаковам във формата на код. After the contest date(s) end you could wrap in a “sorry, this contest is over” text. След конкурса Дата (и) край бихте могли да опаковам в "За съжаление, това състезание е над" текст.

Resources Ресурси
Template Tags/the date - Wordpress Codex - This is for modifying and understanding the_date() parameters in wordpress’s function. Шаблон Tags / датата - WordPress Codex - Това е за модифициране и разбиране the_date () параметри в WordPress неговата функция.
http://us3.php.net/manual/en/function.mktime.php - This is the function we’re using within the date() function to “generate” a time. http://us3.php.net/manual/en/function.mktime.php - Това е функцията, ние използваме по дата () функцията да "генерира" А времето. Note this time is based on your server time. Имайте предвид това време се основава на вашия сървър време. Which means if your server time is an hour behind you, you can adjust for that by doing something like this (still assuming the two month string). date(”Ymd”,mktime(date(”h”) 1,0,0,date(”m”)-2,date(”d”),date(”Y”))); . Което означава, ако вашият сървър, времето е един час зад теб, можеш да се приспособява към това, като правим нещо като това (все още встъпи в два месеца низ). Дата ( "Ymd", mktime (дата ( "Н") 1,0, 0, дата ( "М") -2, дата ( "D"), дата ( "Y ")));.
http://us3.php.net/manual/en/function.date.php - Date function calls/formatting in PHP. http://us3.php.net/manual/en/function.date.php - дата функция повиквания / форматиране на PHP. If you want to change the format of the date, this would be a good place to go. Ако искате да промените формата на датата, това би било добро място да отида. Just replace the configuration of the Ymd I have in there now to whatever format you want based on the chart shown there. Просто замени конфигурацията на Ymd съм там сега, за да независимо от формата, която искате на базата на таблицата е показано тук.

Hope that helps! Надявам се, че помага! Questions about this, post below. Въпросът за това, пункт по-долу. New requests or questions about the way I created this theme please post to the Rob Malon redesigned post . Нови искания или въпроси относно начина, по който съм създал тази тема моля пост на Роб Malon преработени пост.


2 Comment(s) On 2 коментар (а) На

"Display And Hide Content Based On Date Or Age Of Posts - Wordpress Hack" "Показване и скриване на съдържанието въз основа на датата или възрастта на длъжностите - WordPress Hack"
  1. MyAvatars 0,2 Samir - Aug 5, 2008 Samir - 5-ти август 2008 година

    Rob, great post. Роб, супер пост. Thanks for the detailed info. Благодаря за подробната информация. You can never have too many WordPress theme hacks in your arsenal. Никога не можеш да имате твърде много УърдПрес тема хакове в своя арсенал.

  2. MyAvatars 0,2 Graph - Sep 10, 2008 Графика - 10 септември, 2008

    Great information Големите информация



Leave A Comment: Оставете коментар:

Comments RSS Feed Коментари RSS Емисия

7 Minus 2 = 7 минус 2 =

Custom Theme by Rob Malon | Content & Design © 2008 - Rob Malon [dot] Com. Специален тема от Роб Malon | Съдържание и дизайн © 2008 - Роб Malon [точка] СОМ. "));
"));