Come far rivivere vecchi post usando PHP e Crontab (WordPress)
Supponiamo che tu abbia un certo numero di post decenti nel tuo blog e ti stai chiedendo se c’è un modo per pubblicare su twitter/facebook (o altri social network) automaticamente e regolarmente.
Questo non è difficile. Anche se questo post ti guiderà a pubblicare su Twitter, il principio è simile per altri social network. Questo post introduce la funzione PHP per pubblicare su Twitter.
Non vogliamo pubblicare gli stessi contenuti/articoli ancora e ancora in un breve periodo di tempo. Pertanto, dobbiamo creare una tabella SQL che memorizzi la cronologia dei post ripubblicati.
--
-- Table structure for table `twitter`
--
CREATE TABLE IF NOT EXISTS `twitter` (`id` bigint(32) unsigned NOT NULL,
`url` varchar(255) NOT NULL,
`posttime` datetime NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
La tabella ha tre campi, uno è la chiave primaria (incremento automatico), il secondo campo è la posizione dell’URL che è stata ripubblicata e il terzo è la data e l’ora.
Tutti i campi devono essere indicizzati correttamente.
ALTER TABLE `twitter`
ADD PRIMARY KEY (`id`), ADD KEY `url` (`url`,`posttime`), ADD KEY `posttime` (`posttime`);
Ora, se hai un wordpress, devi interrogare i post validi e sceglierne uno a caso.
// database constants
require('db.php');
// twitter function
require('twitter.php');
mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die(mysql_error());
mysql_select_db(DB_NAME);
$today = date("Y-m-d h:i:s");
// get total number of valid posts
$query = "
select
count(1)
from
`wp_posts`
where
(`post_type` = 'page' or `post_type` = 'post') and
(`post_status` = 'publish')
";
$result = mysql_query($query) or die(mysql_error());
$total = mysql_result($result, 0, 0);
$cnt = 0;
if ($total > 0) {
while (1) {
// pick a random npost
$idx = mt_rand(0, $total - 1);
$query = "
select
`post_name`, `post_title`
from
`wp_posts`
where
(`post_type` = 'page' or `post_type` = 'post') and
(`post_status` = 'publish')
limit $idx, 1
";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// post URL
$url = "<a class="vglnk" target="_blank" href="http://www.codingforspeed.com/".$row['post_name']."/" rel="nofollow"><span>http</span><span>://</span><span>www</span><span>.</span><span>codingforspeed</span><span>.</span><span>com</span><span>/".$</span><span>row</span><span>['</span><span>post</span><span>_</span><span>name</span><span>']."/</span></a>";
$title = $row['post_title'];
$query2 = "select date(`posttime`) from `twitter` where `url` = '$url' order by `posttime` desc limit 1";
$result2 = mysql_query($query2) or die(mysql_error());
if (mysql_num_rows($result2) > 0) {
$last = mysql_result($result2, 0, 0);
// last reposted date/time
$diff = abs((strtotime($today) - strtotime($last)) / 24 / 3600);
if ($diff <= 90) {
$cnt ++;
if ($cnt > 16) { // max retry time to avoid endless loop
break;
}
continue; // try next random post
}
}
// record the post in the table
$query = "
insert into `twitter`
set
`url` = '$url',
`posttime` = '$today'
";
mysql_query($query) or die(mysql_error());
$msg = "#Repost ".$title;
echo "$msg $url";
postTwitter($msg, $url);
break;
}
}
L’idea qui è quella di ottenere un post casuale e controllare se è stato ripubblicato negli ultimi 90 giorni (modificare se necessario), in caso contrario, pubblicarlo e registrarlo nel database. Altrimenti, prova i prossimi post casuali fino a quando non sono stati provati un certo numero di volte. Se non sono stati trovati post "validi" di questo tipo (ad es. nessun nuovo articolo per molto tempo), lo rileverà e abbandonerà il ciclo.
Controlla anche questo post per ottenere una riga casuale usando SQL.
La prossima cosa è testarlo correttamente e metterlo nel crontab, ad esempio una volta al giorno.
0 8 * * * php /home/justyy.lai/auto.php > /dev/null 2>&1
La pubblicazione del messaggio su twitter è personalizzabile e ho aggiunto un hash tag "#Repost" per distinguerlo dagli altri post normali. Collego anche il mio account twitter a una pagina facebook, in modo che ogni volta che i twit vengono postati su Twitter, la pagina Facebook anche lo stato è sincronizzato, il che è molto più semplice per me.