[WordPress] wp_remote_get の結果を transient API でキャッシュしておく奴

<?php
function transient_remote_get($url, $expiration = 3600) {
$transient = 'remote_get-' . md5($url);
if ( ! ($response_body = get_transient($transient)) ) {
$response = wp_remote_get($url);
if( !is_wp_error($response) && $response["response"]["code"] === 200 ) {
$response_body = $response["body"];
set_transient($transient, $response_body, $expiration);
} else {
$response_body = false;
}
}
return $response_body;
}

view raw
gistfile1.php
hosted with ❤ by GitHub

[WordPress] wp-cli でユーザパスワード変更

wp-cli 使えば、パスワードがわからなくなったユーザのパスワードを変更することも容易です。

$ cd /path/to/wordpress
$ wp user list
+—–+—————–+————————–+———————————+———————+—————+
| ID | user_login | display_name | user_email | user_registered | roles |
+—–+—————–+————————–+———————————+———————+—————+
| 1 | hogehoge | hogehoge | hogehoge@example.com | 2014-03-20 00:00:00 | administrator |
+—–+—————–+————————–+———————————+———————+—————+
$ wp user update 1 -user_pass=fugafuga
Success: Updated user 1.

view raw
gistfile1.txt
hosted with ❤ by GitHub

参考

[WordPress] WP_ALLOW_REPAIR の罠

http://example.com/wp-admin/maint/repair.php を有効にするには wp-config.php に以下を追記します。

define('WP_ALLOW_REPAIR', true);

これを無効にしようとして define('WP_ALLOW_REPAIR', false); としてもダメです。コメントアウトするか行自体を削除しないといけない。
なぜなら wp-admin/maint/repair.php で以下のように判定してるから。

 :
if ( ! defined( 'WP_ALLOW_REPAIR' ) ) {
        echo '

' . __( 'To allow use of this page to automatically repair database problems, please add the following line to your wp-config.php file. Once this line is added to your config, reload this page.' ) . "

define('WP_ALLOW_REPAIR', true);

"; } elseif ( isset( $_GET['repair'] ) ) { :

ママン、設定値の名前にだまされたよ。

[WordPress] WordPress から backlog API を叩く

<?php
include_once( ABSPATH . WPINC . '/class-IXR.php' );
include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
add_filter( 'http_request_args', function( $args, $url ) {
if ( false !== strpos($url, 'example.backlog.jp') ) {
$args['headers']['Authorization'] = 'Basic '. base64_encode('backlog_user' . ':' . 'backlog_passwd');
}
return $args;
}, 10, 2 );
$ixr_client = new WP_HTTP_IXR_Client( 'https://example.backlog.jp/XML-RPC&#39; );
if ( !$ixr_client->query('backlog.getProjects') ) {
var_dump($ixr_client->getErrorCode());
}
print_r($ixr_client->getResponse());

view raw
gistfile1.php
hosted with ❤ by GitHub

参考
backlog API
WordPress – XMLRPC – IXR client and http Basic Authentication

Contact Form 7 に来たお問い合わせ内容で、Backlog に課題を自動作成するサンプル

<?php
/*
Plugin Name: WP CF7 to Backlog
Plugin URI:
Description:
Author: wokamoto
Version: 0.0.1
*/
include_once( ABSPATH . WPINC . '/class-IXR.php' );
include_once( ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
// new cf7_to_backlog('backlog_spacename', 'backlog_user', 'backlog_passwd', 'backlog_projectkey', (int)backlog_userid);
class cf7_to_backlog {
const API_URL = 'https://%s.backlog.jp/XML-RPC&#39;;
const DEFAULT_TITLE = 'CF7 からの問い合わせ';
private $ixr;
private $backlog_api;
private $backlog_user;
private $backlog_pass;
private $backlog_project;
private $backlog_assignerId;
function __construct( $space_name, $user, $pass, $project_key, $assigner = null ){
add_filter ( 'http_request_args', array($this, 'http_request_args'), 10, 2 );
$this->backlog_api = sprintf(self::API_URL, $space_name);
$this->backlog_user = $user;
$this->backlog_pass = $pass;
$this->ixr = new WP_HTTP_IXR_Client($this->backlog_api);
$this->backlog_project = $this->get_project_id($project_key);
$this->backlog_assignerId = apply_filters('cf7_to_backlog::assigner', intval($assigner));
add_action( 'wpcf7_submit', array($this, 'wpcf7_backlog_submit'), 10, 2 );
add_filter( 'cf7_to_backlog::summary', array($this, 'issue_title') );
}
private function get_project_id( $project_key ){
$this->ixr->query('backlog.getProject', $project_key);
if ( $this->ixr->isError() )
return new WP_Error('get_project_id', $this->ixr->getErrorMessage());
$res = $this->ixr->getResponse();
return
!isset($res['id'])
? new WP_Error('get_project_id', 'unknown error')
: intval($res['id']);
}
private function create_issue($args = array()){
$args['projectId'] = $this->backlog_project;
$args['assignerId']= $this->backlog_assignerId;
$args['summary'] = apply_filters( 'cf7_to_backlog::summary', isset($args['summary']) ? $args['summary'] : self::DEFAULT_TITLE );
$args['due_date'] = apply_filters( 'cf7_to_backlog::due_date', date("Ymd",strtotime("+1 day")) );
$args['issueType'] = apply_filters( 'cf7_to_backlog::issueType', 'タスク' );
$this->ixr->query('backlog.createIssue', $args);
if ( $this->ixr->isError() )
return new WP_Error('create_issue', $this->ixr->getErrorMessage());
return $this->ixr->getResponse();
}
public function issue_title($summary) {
return
$summary != '[your-subject]'
? $summary
: self::DEFAULT_TITLE;
}
public function http_request_args( $args, $url ) {
if ( false !== strpos($url, $this->backlog_api) ) {
$args['headers']['Authorization'] = 'Basic '. base64_encode("{$this->backlog_user}:{$this->backlog_pass}");
}
return $args;
}
public function wpcf7_backlog_submit( $contactform, $result ) {
$cases = (array) apply_filters( 'cf7_to_backlog::submit_if', array( 'mail_sent', 'mail_failed' ) );
if ( empty( $result['status'] ) || ! in_array( $result['status'], $cases ) )
return;
if ( empty( $contactform->posted_data ) )
return;
$fields_senseless = $contactform->form_scan_shortcode(
array( 'type' => array( 'captchar', 'quiz', 'acceptance' ) ) );
$exclude_names = array();
foreach ( $fields_senseless as $tag )
$exclude_names[] = $tag['name'];
$posted_data = $contactform->posted_data;
foreach ( $posted_data as $key => $value ) {
if ( '_' == substr( $key, 0, 1 ) || in_array( $key, $exclude_names ) )
unset( $posted_data[$key] );
}
$email = $this->wpcf7_get_value( 'email', $contactform );
$name = $this->wpcf7_get_value( 'name', $contactform );
$subject = $this->wpcf7_get_value( 'subject', $contactform );
$special_mail_tags = array( 'remote_ip', 'user_agent', 'url', 'date', 'time',
'post_id', 'post_name', 'post_title', 'post_url', 'post_author', 'post_author_email' );
$akismet = isset( $contactform->akismet ) ? (array) $contactform->akismet : null;
$content = '';
$fields = $this->array_flatten( $posted_data );
$fields = array_filter( array_map( 'trim', $fields ) );
$content = implode( "\n", $fields );
$this->create_issue(array(
'summary' => $subject,
'description' => $content,
));
}
private function wpcf7_get_value( $field, $contactform ) {
if ( empty( $field ) || empty( $contactform ) )
return false;
$value = '';
if ( in_array( $field, array( 'email', 'name', 'subject' ) ) ) {
$templates = $contactform->additional_setting( 'flamingo_' . $field );
if ( empty( $templates[0] ) ) {
$template = sprintf( '[your-%s]', $field );
} else {
$template = trim( wpcf7_strip_quote( $templates[0] ) );
}
$value = $contactform->replace_mail_tags( $template );
}
$value = apply_filters( 'cf7_to_backlog::wpcf7_get_value', $value, $field, $contactform );
return $value;
}
private function array_flatten( $input ) {
if ( ! is_array( $input ) )
return array( $input );
$output = array();
foreach ( $input as $value )
$output = array_merge( $output, $this->array_flatten( $value ) );
return $output;
}
}

view raw
gistfile1.php
hosted with ❤ by GitHub

[WordPress] 選択できるデフォルトのインポートツールを制限する

制限する

<?php
add_filter('site_transient_popular_importers_' . get_locale(), function($popular_importers){
if ( is_array( $popular_importers ) && isset($popular_importers['importers']) ) {
// 適宜コメントアウトしてください
unset($popular_importers['importers']['blogger']);
unset($popular_importers['importers']['wpcat2tag']);
unset($popular_importers['importers']['livejournal']);
unset($popular_importers['importers']['movabletype']);
unset($popular_importers['importers']['opml']);
unset($popular_importers['importers']['rss']);
unset($popular_importers['importers']['tumblr']);
unset($popular_importers['importers']['wordpress']);
} else {
// 適宜コメントアウトしてください
$popular_importers = array(
'importers' => array(
'blogger' => array(
'name' => __( 'Blogger' ),
'description' => __( 'Install the Blogger importer to import posts, comments, and users from a Blogger blog.' ),
'plugin-slug' => 'blogger-importer',
'importer-id' => 'blogger',
),
'wpcat2tag' => array(
'name' => __( 'Categories and Tags Converter' ),
'description' => __( 'Install the category/tag converter to convert existing categories to tags or tags to categories, selectively.' ),
'plugin-slug' => 'wpcat2tag-importer',
'importer-id' => 'wp-cat2tag',
),
'livejournal' => array(
'name' => __( 'LiveJournal' ),
'description' => __( 'Install the LiveJournal importer to import posts from LiveJournal using their API.' ),
'plugin-slug' => 'livejournal-importer',
'importer-id' => 'livejournal',
),
'movabletype' => array(
'name' => __( 'Movable Type and TypePad' ),
'description' => __( 'Install the Movable Type importer to import posts and comments from a Movable Type or TypePad blog.' ),
'plugin-slug' => 'movabletype-importer',
'importer-id' => 'mt',
),
'opml' => array(
'name' => __( 'Blogroll' ),
'description' => __( 'Install the blogroll importer to import links in OPML format.' ),
'plugin-slug' => 'opml-importer',
'importer-id' => 'opml',
),
'rss' => array(
'name' => __( 'RSS' ),
'description' => __( 'Install the RSS importer to import posts from an RSS feed.' ),
'plugin-slug' => 'rss-importer',
'importer-id' => 'rss',
),
'tumblr' => array(
'name' => __( 'Tumblr' ),
'description' => __( 'Install the Tumblr importer to import posts &amp; media from Tumblr using their API.' ),
'plugin-slug' => 'tumblr-importer',
'importer-id' => 'tumblr',
),
'wordpress' => array(
'name' => 'WordPress',
'description' => __( 'Install the WordPress importer to import posts, pages, comments, custom fields, categories, and tags from a WordPress export file.' ),
'plugin-slug' => 'wordpress-importer',
'importer-id' => 'wordpress',
),
),
'translated' => true,
);
}
return $popular_importers;
});

まったく表示しない

<?php
add_filter('site_transient_popular_importers_' . get_locale(), function($popular_importers){
return array(
'importers' => array(),
'translated' => true,
);
});

view raw
wp_no_importers.php
hosted with ❤ by GitHub

[WordPress] 「おやおや」と「こどもも」

親カテゴリー「おやおや」とその子カテゴリー「こどもも」があるとします。WordPressでは子カテゴリー「こどもも」にチェックを入れた場合、親カテゴリー「おやおや」にはチェックが入りません。これを親カテゴリーにも自動的にチェックを入れるプラグイン(Parent Category Toggler)はあるのですが、これを過去分にさかのぼってチェックを入れるには?

INSERT INTO wp_term_relationships
SELECT object_id, term_taxonomy_id, 0 AS term_order
FROM (
SELECT DISTINCT r.object_id, p.term_taxonomy_id
FROM wp_term_relationships AS r
INNER JOIN wp_term_taxonomy AS t ON r.term_taxonomy_id = t.term_taxonomy_id
INNER JOIN wp_term_taxonomy AS p ON t.parent = p.term_id
WHERE t.taxonomy = 'category'
AND t.parent > 0 ) AS a
WHERE NOT EXISTS
(SELECT 'x'
FROM wp_term_relationships AS b
WHERE a.object_id = b.object_id
AND a.term_taxonomy_id = b.term_taxonomy_id)
;

view raw
gistfile1.sql
hosted with ❤ by GitHub

[WordPress] VaultPress をリバースプロキシ環境下で使うためのアレコレ

以下を wp-config.php に追記

<?php
define( 'VAULTPRESS_DISABLE_FIREWALL', true );
if ( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
$forwarded_ips = explode( ',', $_SERVER['HTTP_X_FORWARDED_FOR'] );
$_SERVER['REMOTE_ADDR'] = $forwarded_ips[0];
unset( $forwarded_ips );
}

view raw
gistfile1.php
hosted with ❤ by GitHub

あと、リバースプロキシとは関係ないけど wp-admin を IP アドレス制限してるときは、以下の IP を許可してやる必要がある。

207.198.112.0/24
207.198.113.0/24