LoginSignup
0
0

More than 3 years have passed since last update.

【WordPress】その他

Last updated at Posted at 2019-05-28

Transient APIでデータを一時的にキャッシュさせる

概要

Transient APIでデータを一時的にキャッシュさせる

スクリプト

書き込み

set_transient( 'value', $value, 10 * MINUTE_IN_SECONDS );

MINUTE_IN_SECONDS = 60 (秒)

HOUR_IN_SECONDS = 60 * MINUTE_IN_SECONDS (1時間)

DAY_IN_SECONDS = 24 * HOUR_IN_SECONDS (1日)

WEEK_IN_SECONDS = 7 * DAY_IN_SECONDS (1週間)

YEAR_IN_SECONDS = 365 * DAY_IN_SECONDS (1年)

呼び出し

if ( false === ( $value = get_transient( 'value' ) ) ) {
    // Transient が存在しない場合、この部分のコードが実行されます。
    $value = ... // ここで Transient の値を設定し直します
}
// $value に対して処理を行います

「'value'」はユニークな名前にしてください

関連リンク

Transient API


記事イメージ一覧

概要

記事イメージ一覧

施策

/*--------------------------------------------------------
画像詳細ページ
--------------------------------------------------------*/
class imagelistarticle{
}
function image_list_article($p){
    $jary = array();

    $args = array(
        'p' => $p,
        'order' => 'DESC',//ASC or DESC
        'posts_per_page' => 1,
        'numberposts' => -1,
        'post_status' => 'publish'
    );

    $my_query = new WP_Query($args);

    $st = '';

    while ($my_query->have_posts()):$my_query->the_post();
        $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', get_the_content(), $matches);

        foreach ( $matches[1] as $term ) {
            $Ary = new imagelistarticle();

            $attachment_id = get_attachment_id($term);


            $attachment = get_post( $attachment_id );

            if (!preg_match(',' . $term . ',', $st)) {
                $img_ID =  get_attachment_id($term);

                if($img_ID){
                    $Ary->link = '/'. $p .'/'. $attachment->post_name .'/';
                    $Ary->src = $term;
                    $Ary->image = wp_get_attachment_image(get_attachment_id($term));

                    array_push($jary, $Ary);
                }
            }

            $st .= ',' . $term . ',';

        }

    endwhile;

    // 投稿データをリセット
    wp_reset_postdata();

    return $jary;
}

画像リンクをLightboxで表示する

概要

画像リンクをLightboxで表示する

施策

if($('a[href$=".jpg"]')[0] || $('a[href$=".png"]')[0] || $('a[href$=".gif"]')[0]){
    $('a[href$=".jpg"], a[href$=".png"],a[href$=".gif"]').each(function() {
        //aタグ内にimgタグがあるか?
        if( $(this).find('img').length ) {
            $(this).attr( "data-lightbox", "image-" + cnt ); // 画像リンクの場合だけ属性を追加する
            cnt++;
        }
    });
}

メインループ以外の検索

概要

メインループ以外の検索

施策

/*--------------------------------------------------------
// ニュース検索
--------------------------------------------------------*/
class newslist{
}
function news_parse(){

    $Ary = new newslist();

    $Ary->title = get_the_title();
    $Ary->date = get_the_date('Y.m.d');

    $imageUrl = post_custom('news-url');

    $pdf_ID  = get_field('news-pdf');

    $filepath = wp_get_attachment_url( $pdf_ID );//get_attached_file( $pdf_ID );
    $Ary->filepath = $filepath;

    if($imageUrl!=''|| $pdf_ID!='' || get_the_content()!=''){
        $Ary->hasLink = true;
    }else{
        $Ary->hasLink = false;
    }

    $terms = get_the_terms( get_the_ID() , 'news_cat' );
    $cnt = 0;
    foreach ( $terms as $term ) {
        if($cnt==0){
            $Ary->taxname = $term->name;
            $Ary->taxslug = $term->slug;
        }
        $cnt++;
    }


    if($filepath != ''){
        $Ary->url = $filepath;
        $Ary->filesize = '<span>(PDF:' . (floor( filesize( get_attached_file( $pdf_ID ) ) / 1024 * 10 ) / 10) . 'KB)</span>';
        $Ary->more = 'PDF';
    }else if($imageUrl!=''){
        $Ary->url = $imageUrl;

        $info = new SplFileInfo($imageUrl);
        $ext = $info->getExtension();

        if($ext=='pdf'){
            $Ary->more = 'PDF';
            $Ary->filesize = '<span>(PDF:' . (floor( filesize( $_SERVER['DOCUMENT_ROOT'] . $imageUrl ) / 1024 * 10 ) / 10) . 'KB)</span>';
        }else{
            $Ary->more = 'MORE';
            $Ary->filesize = '';
        }

    }else if(get_the_content()!=''){
        $Ary->url = get_the_permalink();
        $Ary->more = 'MORE';
        $Ary->filesize = '';
    }else{
        $Ary->more = '';
        $Ary->filesize = '';
    }


    $imageBlk = get_field('news-blank');
    $Ary->blank = $imageBlk[0];

    if($imageBlk[0] == 'true'){
        $Ary->blank_html = ' target="_blank"';
    }else{
        $Ary->blank_html = '';
    }

    return $Ary;
}
function news_search($taxonomy='',$num=8){
    $jary = array();

    if($taxonomy!=''){
        $tax = array(
            'taxonomy' => 'news_cat',
            'field' => 'slug',
            'terms' => $taxonomy
        );
    }else{
        $tax = '';
    }

    $args = array(
        'post_type' => array('news'),
        'order' => 'DESC',//ASC or DESC
        //'paged' => $paged,
        'posts_per_page' => $num,
        'orderby' => 'date',
        'numberposts' => -1,
        'post_status' => 'publish',
        'tax_query' => array($tax)
    );

    $my_query = new WP_Query($args);

    while ($my_query->have_posts()):$my_query->the_post();

        $Ary = news_parse();
        array_push($jary, $Ary);

    endwhile;

    // 投稿データをリセット
    wp_reset_postdata();

    return $jary;
}

記事投稿時に処理を行う

function myfunction( $new_status, $old_status, $post ) {
//処理する内容
}

add_action( 'transition_post_status', 'myfunction', 10, 3 );

記事内のはじめの画像を調べる

概要

記事内のはじめの画像を調べる

施策

function catch_that_image() {
    global $post, $posts;
    $first_img = '';
    ob_start();
    ob_end_clean();
    $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    $first_img = $matches[1][0];

    if(empty($first_img)){ //Defines a default image
        $first_img = "/img/common/img_blog_noimg.jpg";
    }else{
        $first_img = wp_get_attachment_image_src(get_attachment_id($first_img), 'blog-thumbnail')[0];
    }

    if($first_img==''){
        $first_img = "/img/common/img_blog_noimg.jpg";
    }
    return $first_img;
}

「非公開:」記事をログインしていてもフロントに出さない

概要

「非公開:」記事をログインしていてもフロントに出さない

施策

/*------------------------------------------------------
 * 「非公開:」記事をログインしていてもフロントに出さない
--------------------------------------------------------*/
function parse_query_ex() {
    if (!is_super_admin() && !get_query_var('post_status') && !is_singular()) {
        set_query_var('post_status', 'publish');
    }
}
add_action('parse_query', 'parse_query_ex');

※スーパーユーザーには出ます。


リライトルール

概要

リライトルールを作成

施策

// ルールを追加するときはflush_rules()を忘れないように
function flushRules(){
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}

// 新しいルールを追加
function wp_insertMyRewriteRules($rules)
{
    $newrules = array();

    $newrules['^news/?'] = 'index.php?post_type=news';

    return $newrules + $rules;
}

// 変数idを追加して、WordPressが認識できるようにする
function wp_insertMyRewriteQueryVars($vars)
{
    array_push($vars, 'id');
    return $vars;
}
add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('query_vars','wp_insertMyRewriteQueryVars');
add_filter('init','flushRules');

記事内に別記事埋め込み

概要

記事内に別記事埋め込み

施策

/*--------------------------------------------------------
投稿挿入ショートコード
--------------------------------------------------------*/
function post_includeFunc($atts) {

    extract(shortcode_atts(array(
        'id' => 437,
        'type' => 'others',
        'echo' => 1
    ), $atts));

    $args = array(
        'post_type' => array($type),
        'p' => $id
    );

    $my_query = new WP_Query($args);

    $htm = '';
    while ($my_query->have_posts()):$my_query->the_post();
        $htm .= get_the_content();

        if($echo==1){
            echo get_the_content();
        }
    endwhile;

    // 投稿データをリセット
    wp_reset_postdata();

    if($echo==0) {
        return $htm;
    }
}
add_shortcode('post_include', 'post_includeFunc');

カスタム投稿パーマリンク「/taxonomy/」削除

概要

カスタム投稿パーマリンク「/taxonomy/」削除

施策

/*--------------------------------------------------------
//カスタム投稿パーマリンク「/taxonomy/」削除
--------------------------------------------------------*/
function my_custom_post_type_permalinks_set($termlink, $term, $taxonomy){
    global $wp_query;
    if($wp_query->is_post_type_archive( 'news' )){
        return str_replace('/'.$taxonomy.'/', '/', $termlink);
    }
}
add_filter('term_link', 'my_custom_post_type_permalinks_set',11,3);

ファイルサイズを調べる

概要

ファイルサイズを調べる

施策

functions.php

function formatSizeUnits($bytes) {
    if ($bytes >= 1073741824) {
        $bytes = number_format($bytes / 1073741824,2) . 'GB';
    } elseif ($bytes >= 1048576) {
        $bytes = number_format($bytes / 1048576,1) . 'MB';
    } elseif ($bytes >= 1024) {
        $bytes = number_format($bytes / 1024) . 'KB';
    } elseif ($bytes > 1) {
        $bytes = $bytes . 'bytes';
    } elseif ($bytes == 1) {
        $bytes = $bytes . 'byte';
    } else {
        $bytes = '0 bytes';
    }

    return $bytes;
}

使用方法

formatSizeUnits( filesize( [ファイルパス] ) );

Instagram APIとWordPress連携

Instagram APIのSandboxを利用してWordPressにインスタグラムの写真を表示

この方法は使用できなくなります。

ディベロッパーサイトにアクセス

Instagram Developer Documentation

Register Your Applicationをクリック

instagram01.jpg

Register a New Clientをクリック

instagram02.jpg

Disable implicit OAuth:のチェックを外す

instagram03.jpg

アプリケーション情報を記入

instagram04.jpg

名称 説明
Application Name アプリケーション名(あなたのアプリ名にInstagram、IG、insta、またはgramを使用しないでください。)
Description 説明
Company Name 会社名
Website URL ウェブサイトのURL
Valid redirect URIs 有効なリダイレクトURI(redirect_uriは、アプリケーションを認証するかどうかを選択した後にユーザーをリダイレクトする場所を指定します。)
Privacy Policy URL プライバシーポリシーURL
Contact email 連絡先メールアドレス(Instagramがあなたと連絡を取るために使用できる電子メール。あなたのアプリに関する重要な情報を通知する有効なメールアドレスを指定してください。)

クライアントIDでアクセストークンを取得

instagram05.jpg

ブラウザのアドレル欄に下記URLでアクセス

https://api.instagram.com/oauth/authorize/?client_id=[クライアントID]&redirect_uri=[リダイレクトURL]&response_type=token

Authorizeをクリック

instagram06.jpg

リダイレクトされたURLの「access_token=」以下をコピー

instagram07.jpg

WordPress内にインスタグラム連携用のPHPを記入

SandboxのAPIへのアクセス制限が時間に500件のため、1分間はキャッシュされるように設定

Rate Limits

transient APIを使用する場合

transient API

function load_instagram_data(){

  ///instagram token
    $token = '[コピーしたaccess_token]';

    $userApiUrl = 'https://api.instagram.com/v1/users/self/media/recent/?access_token=' . $token;

    if( false === ( $jary = get_transient( 'insta' ) ) ) {
        $jary = json_decode(@file_get_contents($userApiUrl), true);
        set_transient( 'insta', $jary, 1 * MINUTE_IN_SECONDS );
    }

    return $jary;
}

「'insta'」部分ユニークな名前をしてください。

ファイルに保存する場合

function load_instagram_data(){

    ///instagram token
    $token = '[コピーしたaccess_token]';

    $userApiUrl = 'https://api.instagram.com/v1/users/self/media/recent/?access_token=' . $token;

    $theme_data = wp_get_theme();
    $template   = $theme_data->Template;

    $save_folder = $_SERVER['DOCUMENT_ROOT'] .'/wp-content/themes/'.$template.'/dat/';
    $dat = $save_folder . 'instagram.dat';

    if (file_exists($dat)  ) {
        $min = floor( ( time() - filemtime($dat) )/60 );

        if($min < 1){
            // JSON($json)を連想配列に変換(デコード)する
            $jary = unserialize(@file_get_contents($dat));
            $jary['flg'] = 'cache';
        }else{
            $jary = json_decode(@file_get_contents($userApiUrl), true);
            $jary['flg'] = 'reload';
            file_put_contents($dat, serialize($jary) , LOCK_EX);
        }
    }else{
        $jary = json_decode(@file_get_contents($userApiUrl), true);
        $jary['flg'] = 'reload';
        file_put_contents($dat, serialize($jary) , LOCK_EX);
    }

    return $jary;
}

表示例

<?php
$array = load_instagram_data();
?>
<h2 class="site-description">instagram</h2>
<div class="userPhoto">
  <img src="<?php echo $array['data'][0]['user']['profile_picture']; ?>" alt="">
</div>
<ul class="instagram">
<?php
foreach ($array['data'] as $key => $value) {
  $img = $value['images']['standard_resolution']['url'];
  $link = $value['link'];
  ?>
  <li>
    <a href="<?php echo $link; ?>" target="_blank">
      <?php  if($value['carousel_media']){ ?>
        <div class="icon"></div> //複数枚用アイコン
      <?php } ?>
      <img src="<?php echo $img; ?>">
    </a>
  </li>
  <?php
}
?>
</ul>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0