WordPress

[WordPress]アップロード画像の複数サイズ自動生成停止

下記実行

update wp_options set option_value='0' where option_name = 'thumbnail_size_w';
update wp_options set option_value='0' where option_name = 'thumbnail_size_h';
update wp_options set option_value='0' where option_name = 'medium_size_w';
update wp_options set option_value='0' where option_name = 'medium_size_h';
update wp_options set option_value='0' where option_name = 'large_size_w';
update wp_options set option_value='0' where option_name = 'large_size_h';
update wp_options set option_value='0' where option_name = 'medium_large_size_w';
update wp_options set option_value='0' where option_name = 'medium_large_size_h';

 
functions.phpに下記追加

function disable_image_sizes( $new_sizes ) {
    unset( $new_sizes['1536x1536'] );
    unset( $new_sizes['2048x2048'] );
    unset( $new_sizes['post-thumbnail'] );
    unset( $new_sizes['category-thumb'] );
    unset( $new_sizes['homepage-thumb'] );
    return $new_sizes;
}
add_filter( 'intermediate_image_sizes_advanced', 'disable_image_sizes' );

add_filter( 'big_image_size_threshold', '__return_false' );

[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}");
}

[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 );

[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');


[WordPress]wp_enqueue_script

function my_original_option()
{
    add_menu_page('オリジナルメニュー','オリジナルメニュー','manage_options','my_option','my_option','',30);
}
add_action('admin_menu', 'my_original_option');

function my_option()
{
    include TEMPLATEPATH . DIRECTORY_SEPARATOR . 'my_option.php';
}
function my_register_scripts()
{
    if(is_admin() && !empty($_GET['page']) && $_GET['page']==='my_option') {
        $keyname = 'my_option';
        $result = wp_register_script($keyname, get_template_directory_uri() . '/scripts/admin-custom.js', array('jquery', 'jquery-ui-sortable'));
        wp_enqueue_script($keyname);
    }
}
add_action('init', 'my_register_scripts');

[WordPress]ACF Pro Wysiwyg用関数

public function is_empty_wysiwyg_content($content)
{
    $content = $this->get_string_from_wysiwyg_content($content);
    return $content === '';
}
public function get_wysiwyg_content($content)
{
    return apply_filters('acf_the_content',$content);
}
public function get_string_from_wysiwyg_content($_content)
{
    $is_empty = trim(preg_replace('/<[^>]+?>/','',$_content)) == ' ';
    if($is_empty)
        return '';
    return trim(html_entity_decode(preg_replace('/<[^>]+?>/','',$_content)));
}

[WordPress]タクソノミー、タームから記事数取得

public function get_posts_count_by_taxonomy_slug($taxonomy, $term = '')
{
    global $wpdb;
    $sql = array();
    $sql[] = "SELECT";
    $sql[] = "COUNT(tr.object_id) AS count";
    $sql[] = "FROM $wpdb->term_relationships AS tr";
    $sql[] = "LEFT JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id";
    $sql[] = "LEFT JOIN $wpdb->terms AS t ON tt.term_id = t.term_id";
    $sql[] = "LEFT JOIN $wpdb->posts AS p ON tr.object_id = p.ID";
    $sql[] = "WHERE p.post_status = 'publish'";
    if (!empty($term))
        $sql[] = "AND t.slug ='$term'";
    $sql[] = "AND tt.taxonomy = '$taxonomy'";
    if (empty($term))
        $sql[] = "GROUP BY tr.object_id";

    $posts = $wpdb->get_results(implode(' ', $sql));
    return empty($posts) ? 0 : $posts[0]->count;
}

[WordPress][プラグイン]WordPress Popular Posts

プラグインWordPress Popular Postsによって閲覧数が保存されている時
指定投稿タイプの記事IDを閲覧数の多い順に取得する

public function get_post_ids_order_by_views_wppp($post_type = 'post', $param = array())
{
    $param = array_merge(
        array(
            'posts_per_page' => 5,
            'range' => '1 MONTH',
            'return_posts' => false,
        ),
        $param
    );
    global $wpdb;
    $now = current_time('mysql');
    $interval = "";
    switch ($param['range']) {
        case "yesterday":
            $interval = "1 DAY";
            break;
        case "daily":
            $interval = "1 DAY";
            break;
        case "weekly":
            $interval = "1 WEEK";
            break;
        case "monthly":
            $interval = "1 MONTH";
            break;
        default:
            $interval = $param['range'];
            break;
    }
    $sql[] = "SELECT postid AS ID,SUM(pageviews) AS views,p.post_type";
    $sql[] = "FROM {$wpdb->prefix}popularpostssummary AS pps";
    $sql[] = "LEFT JOIN $wpdb->posts AS p ON pps.postid = p.ID";
    $sql[] = "WHERE view_datetime > DATE_SUB('{$now}', INTERVAL $interval)";
    $sql[] = "AND p.post_type " . (is_array($post_type) ? "IN ('" . implode("','", $post_type) . "')" : "= '$post_type'");
    $sql[] = "AND p.post_status = 'publish'";
    if (!empty($param['post_id'])) {
        $sql[] = "AND postid " . (is_array($param['post_id']) ? "IN (" . implode(",", $param['post_id']) . ")" : "= {$param['post_id']}");
    }
    if (!empty($param['not_post_id'])) {
        $sql[] = "AND postid " . (is_array($param['not_post_id']) ? "NOT IN (" . implode(",", $param['not_post_id']) . ")" : "!= {$param['not_post_id']}");
    }
    $sql[] = "GROUP BY postid";
    $sql[] = "ORDER BY views DESC";
    if (!empty($param['ppp'])) {
        $sql[] = "LIMIT 0,{$param['ppp']}";
    }elseif (!empty($param['posts_per_page'])) {
        $sql[] = "LIMIT 0,{$param['posts_per_page']}";
    }
    $posts = $wpdb->get_results(implode(' ', $sql));
    if ($param['return_posts'])
        return $posts;
    $ids = array();
    foreach ($posts as $post) {
        $ids[] = $post->ID;
    }
    return $ids;
}

[WordPress]Gutenberg下のプレビューURL変更

/**
 * Gutenbergによる投稿プレビューのURL(プレビュー生成中からのリダイレクト先)を変更する
 * WordPress 5.3.2で動作確認
 * @param $response
 * @return array
 */
function my_rest_pre_echo_response($response)
{
    if(!is_user_logged_in())
        return;
    if($response['status'] === 'draft'){
        $response['link'] = '任意のURL';
    }
    return $response;
}
add_filter( 'rest_pre_echo_response', 'my_rest_pre_echo_response', 100 );