別のWordPressの記事を取得し表示させるショートコード ( wpdbでの別データベース接続 )

概要説明

別サイトのWordPressの記事データを表示させるためのカスタマイズ。複数サイト(DB)の指定ができるようにしているのでショートコードにて1ページに複数のWordPressサイトの記事の表示も可能。カスタム投稿のデータを取得したい場合はDB定義情報の中にpost_typeを含めることで投稿、カスタム投稿の調整が可能です。

functions.php
/*----------------------------------------------------
 別のWordPressの記事を取得し表示させるショートコード
----------------------------------------------------*/
if ( !function_exists( 'get_remote_posts' ) ){

    // html調整エリア
    function get_remote_posts( $atts ){

        extract( shortcode_atts( array(
           'db_key' => 'default',
        ), $atts) );

        // 記事データ取得
        $posts = wpdb_get_posts($db_key);

        $posts_html = '';
        if ( $posts ) {

            // データ取得用サンプルなのでhtmlは要調整
            $posts_html .= '<ul>';
            foreach ( $posts as $key => $post ) {
$li = <<<EOD
                <li>
                    <a href="{$post['url']}">
                        <img src="{$post['thumbnail']}"><hr>
                        {$post['title']}<hr>
                        {$post['content']}<hr>
                        {$post['date']}<hr>
                    </a>
                </li>
EOD;
                $posts_html .= $li;
            }
            $posts_html .= '</ul>';
        }
        return $posts_html;
    }

    // アイキャッチ取得
    function get_remote_post_thumbnail( $remote_wpdb, $table, $post ) {

        // サムネイル画像がない場合のデフォルト画像URL指定
        $image_url = 'https://xxxxxxxxxxxxxxxx/img/no-image.gif';

        // サムネイル画像URL取得
        $query     = "SELECT meta_value FROM {$table['postmeta']} WHERE post_id = %d AND meta_key = '_thumbnail_id'";
        $postmeta  = $remote_wpdb->get_row( $remote_wpdb->prepare( $query, $post->ID )  );

        if ( $postmeta ) {
            $query     = "SELECT guid FROM {$table['posts']} WHERE ID = %d";
            $thumbnail = $remote_wpdb->get_row( $remote_wpdb->prepare( $query, $postmeta->meta_value ) );

            if ( $thumbnail ) {
                $image_url = $thumbnail->guid;
            }
        }
        return $image_url;
    }

    // 別DBに接続して記事情報取得
    function wpdb_get_posts( $db_key )
    {
        // 複数定義可能
        $remote_wp['default'] = array(
            'host'     => 'DBホスト情報',
            'database' => 'データベース名',
            'user'     => 'ユーザーID',
            'pass'     => 'パスワード',
            'prefix'   => 'wp_',
            'url'      => '取得元サイトURL',
        );
        $remote_wp['wp2'] = array(
            'host'     => 'DBホスト情報',
            'database' => 'データベース名',
            'user'     => 'ユーザーID',
            'pass'     => 'パスワード',
            'prefix'   => 'wp_',
            'url'      => '取得元サイトURL',
        );

        // 記事取得条件
        $post_status = 'publish'; // 公開
        $post_type   = 'post';    // 投稿データ

        // 接続情報取得
        $remote_db   = $remote_wp[ $db_key ];

        // テーブル情報取得
        $table['posts']     = $remote_db['prefix'].'posts';
        $table['postmeta']  = $remote_db['prefix'].'postmeta';

        // DB接続
        $remote_wpdb = new wpdb( $remote_db['user'], $remote_db['pass'], $remote_db['database'], $remote_db['host']);

        // prefix 設定
        $remote_wpdb->set_prefix( $remote_db['prefix'] );

        // 記事データ取得
        $query = "SELECT * FROM {$table['posts']} WHERE post_status = %s AND post_type = %s";
        $posts = $remote_wpdb->get_results( $remote_wpdb->prepare( $query, $post_status, $post_type ) );

        $post_list = array();
        foreach ($posts as $post) {

            // 表示用データ整形
            $post_list[] = [
                'post_id'      => $post->ID,
                'title'        => $post->post_title,
                'date'         => date_i18n('Y.m.d', strtotime($post->post_date)),
                'content'      => $post->content,
                'url'          => $remote_db['url'].'/?p='.$post->ID,
                'thumbnail'    => get_remote_post_thumbnail($remote_wpdb,$table,$post),
            ]; 
        }

        return $post_list;
    }

    add_shortcode('remote_posts', 'get_remote_posts');
}

データベース接続情報を設定

functions.php
$remote_wp['任意のサイトID'] = array(
    'host'     => 'DBホスト情報',
    'database' => 'データベース名',
    'user'     => 'ユーザーID',
    'pass'     => 'パスワード',
    'prefix'   => 'wp_',
    'url'      => '取得元サイトURL',
);

[remote_posts] この場合は $remote_wp[‘default’] で設定しているDBに接続します

[remote_posts db_key=wp2] この場合は $remote_wp[‘wp2’] で設定しているDBに接続します

記事、カスタム記事をサイトごとに指定したい場合

functions.php
$remote_wp['任意のサイトID'] = array(
    'host'     => 'DBホスト情報',
    'database' => 'データベース名',
    'user'     => 'ユーザーID',
    'pass'     => 'パスワード',
    'prefix'   => 'wp_',
    'url'      => '取得元サイトURL',
    'post_type'=>'news',
);
$remote_db   = $remote_wp[ $db_key ];

// 記事取得条件
$post_status = 'publish'; // 公開
$post_type   = $remote_db['post_type'];

WordPress Developer Resources

関連機能

  1. WordPress ワンポイントメッセージ表示ショートコード

  2. WordPress 外部リンクのnofollowや別ブラウザ表示設定を表示の際に一括で変更できるプラグイン WP External Links

  3. 表示前にフックして出力テキストを置換する

サイドバー

よく使うカスタマイズ

最近の記事

アニメの名言集

天才は嫌いだ
積み重ねたものの美しさが無い

葬送のフリーレン
by リュグナー

Profile

PAGE TOP
Amazon プライム対象