WordPress

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

[WordPress]独自設定画面で指定DBからデータ取得

functions.php

<?php
function my_menu()
{
    add_menu_page('独自設定画面','my menu','manage_options','my_menu','my_options_page','',58);
}
add_action('admin_menu', 'my_menu');

function my_options_page()
{
    $wpm = new ThisCaseModel();
    $wpdb = new wpdb('DBID','DBPW','DBNAME','DBHOST');

    $page = empty($_GET['_page']) ? 1 : $_GET['_page'];
    $sql = array();
    $sql[] = "SELECT u.id,u.name";
    $sql[] = "FROM users AS u";
    $sql[] = "LEFT JOIN others AS o ON u.id = o.user_id";
    $sql[] = "WHERE o.id IS NOT NULL";
    $sql[] = "ORDER BY u.id ASC";
    $sql[] = "LIMIT " . $wpm->get_sql_limit_value_by_page($page,20);
    $users = $wpdb->get_results(implode(" ",$sql));
    
    array_pop($sql);
    array_pop($sql);
    $sql[0] = "SELECT COUNT(*) AS count";
    $count = $wpdb->get_results(implode(" ",$sql));
    $page_info = $wpm->get_page_no_info($page,$count[0]->count,20);
    $page_numbers = $wpm->get_page_numbers_for_pager((int)$page_info['current'],(int)$page_info['last_page_no']);
    
    include TEMPLATEPATH . DIRECTORY_SEPARATOR . 'admin-my_menu.php';
}

admin-my_menu.php

<style>
    .users,.users th,.properties td{
        border-collapse: collapse;
        border:1px solid #ccc;
    }
    .users th,.users td{
        padding: 3px 5px;
    }
    .pager{
        display: flex;
    }
    .pager a{
        display: block;
        border:1px solid #ccc;
        margin-right: 5px;
        padding: 3px 10px;
    }
    .pager a:link{
        text-decoration: none;
    }
</style>
<div class="container">
    <h2>my menu</h2>
    <div>
        <div>件数:<?php echo $page_info['count'];?></div>
        <div><?php echo $page_info['current'];?>/<?php echo $page_info['last_page_no'];?></div>
    </div>
    <table class="users">
        <tr>
            <th>ID</th>
            <th>name</th>
        </tr>
        <?php foreach ($users as $user):?>
            <tr>
                <td><?php echo $wpm->esc_html($user->id);?></td>
                <td><?php echo $wpm->esc_html($user->name);?></td>
            </tr>
        <?php endforeach;?>
    </table>
    <div class="pager">
        <?php foreach ($page_numbers as $page_number):?>
            <?php if(empty($page_number)):?>
                …
            <?php else:?>
                <a href="<?php echo $wpm->get_url_by_current_url($page_number<2 ? array('exclude_keys'=>array('_page')) : array('exclude_keys'=>array('_page'),'add_values'=>array('_page'=>$page_number)));?>"><?php echo $page_number;?></a>
            <?php endif;?>
        <?php endforeach;?>
    </div>
</div>

[WordPress]新規ユーザ

INSERT INTO wp_users(user_login,user_pass,user_nicename,user_email) VALUES ('ユーザID',MD5('パスワード'),'wp_master','wp_master@master.com');
SET @last_id = LAST_INSERT_ID();
INSERT INTO wp_usermeta(user_id,meta_key,meta_value) VALUES (@last_id,'wp_capabilities','a:1:{s:13:"administrator";b:1;}');

[WordPress]ショートコード#1

function sc_get_template($atts) {
    $param = shortcode_atts( array(
        'file' => '',
    ), $atts );
    $param['file'] = ltrim($param['file'],'/.');
    $file = TEMPLATEPATH . DIRECTORY_SEPARATOR . $param['file'];
    if(!file_exists($file))return '';
    ob_start();
    include($file);
    $contents = ob_get_contents();
    ob_end_clean();
    return $contents;
}
add_shortcode('get_template', 'sc_get_template');
[get_template file="module/_head.php"]

[WordPress]初期設定

update wp_options set option_value='/manage' where option_name = 'siteurl';
update wp_options set option_value='/' where option_name = 'home';
update wp_options set option_value='/uploads' where option_name = 'upload_url_path';
update wp_options set option_value='../uploads' where option_name = 'upload_path';
update wp_options set option_value='' where option_name = 'blogdescription';
update wp_options set option_value='0' where option_name = 'start_of_week';
update wp_options set option_value='Y/m/d' where option_name = 'date_format';
update wp_options set option_value='H:i' where option_name = 'time_format';
update wp_options set option_value='closed' where option_name = 'default_comment_status';
update wp_options set option_value='closed' where option_name = 'default_ping_status';
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 = 'uploads_use_yearmonth_folders';
update wp_options set option_value='/%postname%/' where option_name = 'permalink_structure';

plguin require

Advanced Custom Fields PRO
Custom Post Type UI
Scheduled Post Trigger
User Role Editor
WP Term Order
Duplicate Post

plugin option

Radio Buttons for Taxonomies
Parent Category Toggler
Adjust Admin Categories

[PHP]get_image_rgb

public function get_image_rgb($image_path,$x=0,$y=0)
{
    if(!is_readable($image_path))
        return false;
    $im = imagecreatefrompng($image_path);
    $rgb = imagecolorat($im, $x, $y);
    $r = ($rgb >> 16) & 0xFF;
    $g = ($rgb >> 8) & 0xFF;
    $b = $rgb & 0xFF;
    return array(
        'r' => $r,
        'g' => $g,
        'b' => $b,
    );
}