...
✅ Notizie, temi, plugin WEB e WordPress. Qui condividiamo suggerimenti e le migliori soluzioni per siti web.

Come creare un plugin per il feed Twitter di WordPress WordPress

13

Inutile dire quanto sia popolare Twitter? Molti siti Web stanno mostrando i loro ultimi tweet agli utenti. Normalmente, questo tweet viene posizionato nella barra laterale o in un piè di pagina. Nel post di oggi, creeremo un semplice plugin per WordPress che mostra gli ultimi tweet dove vuoi. Creeremo uno shortcode che può essere posizionato ovunque sul tuo sito.

Come creare un plugin

Creare un plugin per WordPress non è una scienza missilistica. Un uomo che conosce PHP e WordPress può creare facilmente il plugin. Per il nostro compito, sto creando una cartella con il nome "twitter-api" nella directory "wp-content/plugins".

Successivamente, creo "twitter-api.php" e lo inserisco nella cartella "plugins/twitter-api". Il nostro file plugin ‘twitter-api.php’ ha bisogno di alcuni commenti, quindi lo aggiungo nel formato sottostante.

/*
Plugin Name: Twitter API
Plugin URI: https://artisansweb.net
Description: This plugin will fetch your latest tweets and display it using shortcode [tweets]
Version: 1.0
Author: Sajid
Author URI: https://artisansweb.net
License: GPLv2 or later
Text Domain: artisansweb
*/

Dopo aver aggiunto il commento sopra, il nostro plugin apparirà nella pagina dei plugin da dove possiamo attivarlo. Ma poiché non abbiamo scritto alcun codice, viene semplicemente attivato ma non fa nulla. Aggiungeremo molto codice nel nostro plugin. Ma per ora, creiamo solo la struttura di base del nostro plugin.

class Twitter_API {
    public function __construct() {
 
    }
}

Per evitare l’accesso diretto ai file PHP del nostro plugin, dovremmo aggiungere una riga sotto dopo il commento del nostro plugin.

defined( 'ABSPATH') or die( 'No script kiddies please!' );

Installa la libreria PHP di Twitter

Twitter fornisce API REST per gli sviluppatori. Per il nostro plugin, utilizziamo una popolare libreria per Twitter che è costruita in PHP. Ecco l’URL di git-hub per la libreria:https://github.com/abraham/twitteroauth

Per installare questa libreria aprirò un prompt dei comandi nella mia cartella "plugins/twitter-api" ed eseguirò il comando seguente.

composer require abraham/twitteroauth

Dopo aver installato la libreria, inserirò le righe sottostanti nel nostro file ‘twitter-api.php’.

require('vendor/autoload.php');
use AbrahamTwitterOAuthTwitterOAuth;

Ora è il momento di registrare la nostra applicazione Twitter. Per creare un’applicazione, vai su Twitter Apps e segui i passaggi seguenti.

  • Fare clic sul pulsante "Crea nuova app".
  • Compila i campi Nome, Descrizione, Sito web.
  • Accetta il contratto e fai clic sul pulsante "Crea la tua applicazione Twitter".
  • Nella pagina successiva, fai clic sulla scheda "Chiavi e token di accesso". In questa scheda troverai la chiave del consumatore e il segreto del consumatore. Copia questi dettagli e conservali in un luogo sicuro.
  • Nella stessa scheda vedrai la sezione "Il tuo token di accesso". Fare clic sul pulsante "Crea token di accesso".
  • A questo punto, copia il tuo token di accesso e il segreto del token di accesso. Tieni questi dettagli al sicuro.

Abbiamo creato la nostra applicazione Twitter e siamo anche pronti con le nostre chiavi API. Per utilizzare questi dettagli nel nostro plugin, dobbiamo prima memorizzarli. Per questo, stiamo creando una pagina di opzioni per il nostro plugin. Quindi aggiungo sotto il codice nel nostro file.

function __construct() {
    add_action( 'admin_menu', array($this, 'ta_plugin_menu') );
}
 
function ta_plugin_menu() {
    add_options_page('Twitter API', 'Twitter API', 'manage_options', 'twitter_api', array($this, 'ta_settings_page'));
}
 
function ta_settings_page() {
    require_once('inc/ta-settings.php');    
}

Il codice sopra aggiungerà il nostro menu chiamato "API Twitter" in Impostazioni in una dashboard. A questo punto, dobbiamo creare la directory ‘inc’ e inserire il file ‘ta-setting.php’ al suo interno.

Nel file ‘ta-setting.php’ daremo la possibilità di memorizzare i dettagli della nostra API Twitter. Sto aggiungendo sotto il codice in questo file. Stiamo recuperando il valore (che memorizziamo nel passaggio successivo) per ogni campo dal database.

<h1><?php _e('Twitter Information', 'artisansweb'); ?></h1>
<form method="post">
    <table class="form-table">
        <tbody>
            <tr>
                <th scope="row"><label for="blogname"><?php _e('Consumer Key', 'artisansweb'); ?></label></th>
                <td><input name="ta_consumer_key" id="ta_consumer_key" value="<?php if(get_option('ta_consumer_key')) echo get_option('ta_consumer_key'); ?>" class="regular-text" type="text"></td>
            </tr>
            <tr>
                <th scope="row"><label for="blogname"><?php _e('Consumer Secret', 'artisansweb'); ?></label></th>
                <td><input name="ta_consumer_secret" id="ta_consumer_secret" value="<?php if(get_option('ta_consumer_secret')) echo get_option('ta_consumer_secret'); ?>" class="regular-text" type="text"></td>
            </tr>
            <tr>
                <th scope="row"><label for="blogname"><?php _e('Access Token', 'artisansweb'); ?></label></th>
                <td><input name="ta_access_token" id="ta_access_token" value="<?php if(get_option('ta_access_token')) echo get_option('ta_access_token'); ?>" class="regular-text" type="text"></td>
            </tr>
            <tr>
                <th scope="row"><label for="blogname"><?php _e('Access Token Secret', 'artisansweb'); ?></label></th>
                <td><input name="ta_access_token_secret" id="ta_access_token_secret" value="<?php if(get_option('ta_access_token_secret')) echo get_option('ta_access_token_secret'); ?>" class="regular-text" type="text"></td>
            </tr>
            <tr>
                <th scope="row"><label for="blogname"><?php _e('Number of Tweets', 'artisansweb'); ?></label></th>
                <td><input name="ta_no_of_tweets" id="ta_no_of_tweets" value="<?php if(get_option('ta_no_of_tweets')) echo get_option('ta_no_of_tweets'); ?>" class="regular-text" type="number"></td>
            </tr>
        </tbody>
    </table>
    <p class="submit">
        <input name="ta-submit" id="submit" class="button button-primary" value="<?php _e('Save Changes', 'artisansweb'); ?>" type="submit">
    </p>
</form>

In questa pagina, inseriamo i dettagli dell’API che dobbiamo salvare nel database. Quindi ho usato l’azione "init" e ho aggiunto la logica di invio nella funzione di callback.

add_action('init', array($this, 'ta_submit_callback')); //add this code in constructor
 
function submit_callback() {
    if (isset($_POST['ta-submit'])) {
        update_option( 'ta_consumer_key', $_POST['ta_consumer_key'] );
        update_option( 'ta_consumer_secret', $_POST['ta_consumer_secret'] );
        update_option( 'ta_access_token', $_POST['ta_access_token'] );
        update_option( 'ta_access_token_secret', $_POST['ta_access_token_secret'] );
        update_option( 'ta_no_of_tweets', $_POST['ta_no_of_tweets'] );
    }
}

In questa fase, abbiamo completato le impostazioni di back-end richieste per il nostro plugin. Ora andiamo al front-end dove dobbiamo visualizzare gli ultimi tweet. Stiamo creando shortcode in modo da poter visualizzare i tweet dove vogliamo semplicemente inserendo il nostro shortcode. Nel costruttore, metterò sotto la riga di codice.

//add this code in constructor
add_shortcode('tweets', array($this, 'ta_latest_tweets'));
 
if(get_option('ta_consumer_key')) {
    $this->consumer_key = get_option('ta_consumer_key');
}
if(get_option('ta_consumer_secret')) {
    $this->consumer_secret = get_option('ta_consumer_secret');
}
if(get_option('ta_access_token')) {
    $this->access_token = get_option('ta_access_token');
}
if(get_option('ta_access_token_secret')) {
    $this->access_token_secret = get_option('ta_access_token_secret');
}
$this->ta_no_of_tweets = get_option('ta_no_of_tweets')? get_option('ta_no_of_tweets'): 3;

Stiamo anche recuperando i dettagli dell’API nel costruttore. Dovremmo dichiarare le variabili di classe come di seguito.

protected $consumer_key = '', $consumer_secret = '', $access_token = '', $access_token_secret = '', $ta_no_of_tweets;

Successivamente, dovremmo definire la nostra funzione di callback shortcode.

function ta_latest_tweets() {
    $connection = new TwitterOAuth($this->consumer_key, $this->consumer_secret, $this->access_token, $this->access_token_secret);
 
    $arr_tweets = $connection->get("statuses/user_timeline", ["count" => ($this->ta_no_of_tweets), "exclude_replies" => true]);
 
    if ($arr_tweets && !empty($arr_tweets)) {
        ?>
        <ul class="tweet-wrap">
            <?php
            foreach ($arr_tweets as $tweet) {
                ?>
                <li>
                    <div>
                        <img src="<?php echo $tweet->user->profile_image_url; ?>">
                        <strong><?php echo $tweet->user->name ?></strong> @<span><?php echo $tweet->user->screen_name; ?></span>
                    </div>
                    <p><?php echo $tweet->text; ?></p>
                </li>
                <?php
            }
            ?>
        </ul>
        <?php
    }
}

Stiamo aggiungendo un po’ di GUI per il nostro elenco di tweet. Quindi aggiungo il file CSS seguendo il modo.

add_action('wp_enqueue_scripts', array($this, 'ta_include_css')); //add it in constructor
 
function ta_include_css() {
    wp_register_style( "ta-custom-style", plugins_url('/twitter-api'). "/css/custom.css", array(), false, "all" );
    wp_enqueue_style( "ta-custom-style" );
}

Nel mio file CSS, aggiungo di seguito le proprietà per la classe ‘tweet-wrap’. Se lo desideri, puoi aggiungere più CSS secondo le tue necessità.

.tweet-wrap{
    width: 300px;
    list-style-type: none;
}

Questo è tutto, abbiamo completato il nostro plugin che mostra gli ultimi tweet. È possibile scaricare un file zip di un plug-in facendo clic sul collegamento "Ottieni codice plug-in" di seguito.

Ottieni codice plugin

Fonte di registrazione: artisansweb.net

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More