[WordPress]get_post_by_post_name

public function get_post_by_post_name($post_name, $post_type = '', $post_status = 'publish')
{
    global $wpdb;
    $sql = array();
    $sql[] = "SELECT p.*";
    $sql[] = "FROM $wpdb->posts AS p";
    $sql[] = "WHERE p.post_name " . $this->__get_sql_for_in($post_name);
    if (!empty($post_type))
        $sql[] = "AND p.post_type = '$post_type'";
    if(!empty($post_status))
        $sql[] = "AND p.post_status = '$post_status'";
    $result = $wpdb->get_results(implode(' ', $sql));
    if (empty($result))
        return null;
    return is_array($post_name) ? $result : $result[0];
}
protected function __get_sql_for_in($values, $is_number = false)
{
    $quote    = $is_number ? "" : "'";
    $is_array = is_array($values);
    $not      = ($is_array && is_string($values[0]) && preg_match('/^.*\!=.+$/',$values[0])) || (!$is_array && is_string($values) && preg_match('/^.*\!=.+$/',$values));
    $in       = $not ? ' NOT IN' : ' IN';
    $eq       = $not ? '!=' : '=';
    if($is_array){
        foreach ($values as $i => $value) {
            $values[$i] = preg_replace('/^(\!=|=)/', '', esc_sql($value));
            $values[$i] = preg_replace('/^ /', '', esc_sql($value));
        }
    }else{
        $values = preg_replace('/^(\!=|=)/','',esc_sql($values));
        $values = preg_replace('/^ /','',esc_sql($values));
    }
    return $is_array && 1 < count($values) ? "{$in} ({$quote}" . implode("{$quote},{$quote}", $values) . "{$quote})" : ($is_array ? "{$eq} {$quote}{$values[0]}{$quote}" : "{$eq} {$quote}$values{$quote}");
}

[GAS]セルの値をコピー

function copy_values() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var get_range;
  var set_range;
  for(var i = 4 ; i < 30 ; i+=2){
    get_range = sheet.getRange("J"+i+":K"+i);
    set_range = sheet.getRange("J"+(i+1)+":K"+(i+1));
    set_range.setValues(get_range.getValues());
  }
}

[PHP]get_url_by_regex

public function get_url_by_regex($url = null,$replaces = null,$suffix = null)
{
    $tmp = explode('?',empty($url) ? $_SERVER['REQUEST_URI'] : $url);
    $url = 0<count($tmp) ? array_shift($tmp) : '';
    $tmp = 0<count($tmp) ? array_pop($tmp) : '';
    $tmp = explode('&',$tmp);
    for($i=0;$i<count($replaces);$i+=2){
        foreach ($tmp as $j => $q){
            $tmp[$j] = preg_replace($replaces[$i],$replaces[$i+1],$q);
        }
    }
    $tmp = array_diff($tmp,array(''));
    $is_empty = empty($tmp);
    return $url.($is_empty?'':'?'.implode('&',$tmp)) . (is_null($suffix)?'':($is_empty?'?':'&').preg_replace('/^[\?&]/','',$suffix));
}

[SSH]SSHトンネル@WinSCP

SFTP
xxx.xxx.xxx.xxx
22
ID:xxxxxx
PW:yyyyyy
・設定
-トンネル
チェック:SSHトンネルを経由して接続する
nnn.nnn.nnn.nnn 50001
ID:mmmmmm
PW:pppppp
ローカルトンネルポート 自動選択
秘密鍵 id_rsa.ppk
-SSH 認証
チェック エージェントの転送を許可する
秘密鍵 filename.ppk

[PHP]CSV出力@メモリ節約

$csvfile = date('YmdHis') . ".csv";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . $csvfile);
$fp = fopen('php://output','w');
stream_filter_append($fp, 'convert.iconv.UTF-8/CP932', STREAM_FILTER_WRITE);
fputcsv($fp, array('A','B','C'));
fclose($fp);

[PHP,Ruby]Instagram Graph API

PHP

<?php
function echo_json_by_filename($filename)
{
    header("Content-Type: application/json; charset=utf-8");
    if(is_readable($filename)) {
        readfile($filename);
    }else{
        echo '{data:[]}';
    }
}
$businessID          = '111111';
$hashTagID           = '17843677603040508';//パスタ
$targetInstaUsername = isset($_GET['u']) ? $_GET['u'] : '';
$targetFileNo        = isset($_GET['no']) ? $_GET['no'] : '';
$apiBaseUrl          = 'https://graph.facebook.com/v5.0/';
$accessToken         = 'abcdefg';
$urlForHashTag       = "{$apiBaseUrl}{$hashTagID}/recent_media?user_id={$businessID}&fields=id,media_type,media_url,permalink,like_count,comments_count&limit=50&access_token={$accessToken}";
$urlForUsername      = "{$apiBaseUrl}{$businessID}?fields=business_discovery.username({$targetInstaUsername}){id,followers_count,media_count,ig_id,media{caption,permalink,username,media_url,media_type,like_count,comments_count,timestamp,id}}&access_token={$accessToken}";
$urls                = array($urlForHashTag,$urlForUsername);
$nos                 = array_keys($urls);
$filename            = dirname(__FILE__) . "/insta{$targetFileNo}.json";
if(empty($targetInstaUsername) || !is_numeric($targetFileNo) || !in_array($targetFileNo,$nos)){
    echo_json_by_filename($filename);
    exit;
}
if(file_exists($filename)){
    $t = filemtime($filename);
    if($t === false || abs($t - time()) < 60){
        echo_json_by_filename($filename);
        exit;
    }
    if(unlink($filename) === false){
        echo_json_by_filename($filename);
        exit;
    }
}
$data = file_get_contents($urls[$targetFileNo]);
file_put_contents($filename,$data);
header("Content-Type: application/json; charset=utf-8");
echo $data;

Ruby

#!/Ruby23-x64/bin/ruby
# coding: utf-8
ENV['SSL_CERT_FILE'] = File.expand_path('/cert/cacert.pem')
require "cgi"
require "net/https"
require "uri"
require "date"
def echo_json_by_filename(filename)
	puts "Content-Type: application/json; charset=utf-8\n\n"
    if File.exist?(filename) then
        File.open(filename, "r") do |f|
          puts f.read
        end
    else
        puts "{data:[]}"
    end
end
cgi = CGI.new
businessID          = "111111"
hashTagID           = "17843677603040508"#パスタ
targetInstaUsername = cgi["u"]
targetFileNo        = cgi["no"]
apiBaseUrl          = "https://graph.facebook.com/v5.0/"
accessToken         = "abcdefg"
urlForHashTag       = apiBaseUrl + hashTagID + "/recent_media?user_id="+businessID+"&fields=id,media_type,media_url,permalink,like_count,comments_count&limit=50&access_token=" + accessToken
urlForUsername      = apiBaseUrl + businessID + "?fields=business_discovery.username("+targetInstaUsername+"){id,followers_count,media_count,ig_id,media{caption,permalink,username,media_url,media_type,like_count,comments_count,timestamp,id}}&access_token=" + accessToken
filename            = "./insta"+targetFileNo+".json"
if targetInstaUsername.empty? || targetFileNo.empty? then
	echo_json_by_filename(filename)
	exit
end
if File.exist?(filename) then
	gap = DateTime.now.to_time - File.mtime(filename)
	if gap < 60 then
		echo_json_by_filename(filename)
		exit
	end
	File.delete(filename)
end
uri = URI.parse urlForUsername
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
req = Net::HTTP::Get.new uri.request_uri
res = http.request req
file = File.open(filename,"w")
file.puts(res.body)
puts "Content-Type: application/json; charset=utf-8\n\n"
puts res.body
exit

[WordPress]wp_head不要タグ削除

remove_action( 'wp_head', 'wp_resource_hints', 2 );
remove_action( 'wp_head', 'rest_output_link_wp_head', 10, 0 );
remove_action( 'wp_head', 'feed_links_extra', 3);
remove_action( 'wp_head', 'wp_generator');
remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_head', 'wp_print_styles', 8 );

[Apache].htaccessクエリ置換

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} (^|.*&)id=100($|[^0-9])(.*)
RewriteRule ^search.*$ http://%{HTTP_HOST}%{REQUEST_URI}?%1id=200%2%3 [R=301,L]
</IfModule>

id=100をid=200に置換してリダイレクト
id以外のクエリはそのまま

[WordPress]メニュー削除

function remove_noneed_menus()
{
    global $menu;
    global $submenu;

    unset($menu[5]);  // 投稿
    //unset($menu[20]);  // 固定ページ
    unset($menu[25]);  // コメント
}
add_action('admin_menu', 'remove_noneed_menus');

[WordPress]テンプレ切替

function add_user_rewrite_rules()
{
    add_rewrite_rule("^post_type1/?$", "index.php?post_type=post_type1&mode=archive", 'top');
    add_rewrite_rule("^post_type1/article/([^\/]+)/?$", 'index.php?post_type=post_type1&name=$matches[1]&mode=single', 'top');
    add_rewrite_rule("^post_type2/?$", "index.php?post_type=post_type2&mode=archive", 'top');
    add_rewrite_rule("^post_type2/(\d+)/?$", 'index.php?post_type=post_type2&p=$matches[1]&mode=single', 'top');
}
add_action('init', 'add_user_rewrite_rules');

function add_user_routes_query_vars($query_vars)
{
    $query_vars[] = 'mode';
    $query_vars[] = 'param';
    return $query_vars;
}
add_filter('query_vars', 'add_user_routes_query_vars');

/**
 * is_single,is_archiveの返値が確定する前に処理
 * @param $query
 */
function my_parse_request($query)
{
    if(is_admin())
        return;
    
    if($query->query_vars['post_type'] === 'post_type1') {
        $query->query_vars['posts_per_page'] = 10;
    }else if($query->query_vars['post_type'] === 'post_type2') {
        $query->query_vars['posts_per_page'] = 20;
    }else if($query->query_vars['post_type'] === 'post_type3'){
    }
}
add_action( 'parse_request', 'my_parse_request');

function my_pre_get_posts( $query )
{
    if ( is_admin() || ! $query->is_main_query() ){
        return;
    }
    if($query->query['post_type'] === 'post_type1') {
        if (!empty($_GET['api'])) {
            if(!empty($_GET['count']) && preg_match('/^\d+$/',$_GET['count'])){
                $query->set('posts_per_page',$_GET['count']);
            }else{
                $query->set('posts_per_page',3);
            }
        }
    }else if($query->query['post_type'] === 'post_type2') {
        if (!empty($_GET['api'])) {
            if (isset($_GET['cate'])) {
                $tax_query[] = array(
                    'taxonomy' => 'tax_type',
                    'terms'    => array($_GET['cate']),
                    'field'    => 'slug',
                    'operator' => 'IN');
                $query->set('tax_query', array('relation' => 'OR', $tax_query));
            }
            if(!empty($_GET['count']) && preg_match('/^\d+$/',$_GET['count'])){
                $query->set('posts_per_page',$_GET['count']);
            }else{
                $query->set('posts_per_page',3);
            }
        }else if (isset($query->query['param'])) {
            $tax_query[] = array(
                'taxonomy' => 'tax_type',
                'terms'    => array($query->query['param']),
                'field'    => 'slug',
                'operator' => 'IN');
            $query->set('tax_query', array('relation' => 'OR', $tax_query));
        }
    }
}
add_action('pre_get_posts','my_pre_get_posts');

/**
 * テンプレートファイル切替
 * @param $template
 * @return mixed
 */
function my_template_include($template)
{
    global $wp_query;
    if($wp_query->query['post_type'] === 'post_type1' && isset($wp_query->query['mode']) && $wp_query->query['mode'] === 'top') {
        $bn = basename($template);
        return preg_replace("/{$bn}$/","index-post_type1.php",$template);
        
    }else if($wp_query->query['post_type'] === 'post_type2' && isset($wp_query->query['mode']) && $wp_query->query['mode'] === 'top'){
        $bn = basename($template);
        return preg_replace("/{$bn}$/","archive-post_type2.php",$template);

    }else if($wp_query->query['post_type'] === 'post_type3'){
        if($wp_query->query['mode'] === 'single'){
            $bn = basename($template);
            return preg_replace("/{$bn}$/","single-post_type3.php",$template);
        }
    }
    return $template;
}
add_filter('template_include','my_template_include');