ちょっとしたアイディアを試したいときに、head要素に、cssやjavascriptのリンクを作成し、リンク先に、cssのルールやhavascriptのコードを記述する事ができるtemplate_redirectを使ったスニペットです
コードを実行すると
<link rel='stylesheet' id='nobita-extend-style-css' href='http://example.com/wp/?nobita_css=1&ver=3.6.1' type='text/css' media='all' />
といったリンクが作成されて、リンクをクリックすると
body{background:#ccc;}
が表示されます(設定をjsにすれば、javascriptも書けるかも)
テーマのfunctions.phpに
<?php
define('NOBITA_QUERY', 'nobita_css' );
define('NOBITA_VALUE_TYPE', 'css'); //または、js
$nobita_external_link_value= 'body{background:#ccc;}';
//$nobita_external_link_value= 'alert( "hello" )';
//ここまで設定
add_action( 'after_setup_theme', 'nobita_setup_theme' );
function nobita_setup_theme(){
//クエリを登録
add_filter('query_vars','nobita_extend_query');
//ヘッダーにリンクを追加
add_action( 'wp_enqueue_scripts', 'nobita_add_style_link', 99 );
//リンクが呼ばれた時に、必要な内容を表示し終了する
add_action( 'template_redirect', 'nobita_external_link_value' );
}
function nobita_extend_query( $vars ) {
$vars[]= NOBITA_QUERY;
return $vars;
}
function nobita_add_style_link() {
if( NOBITA_VALUE_TYPE== 'css' ){
wp_register_style( 'nobita-extend-style', sprintf('/?%1$s=1', NOBITA_QUERY ) );
wp_enqueue_style( 'nobita-extend-style' );
} elseif ( NOBITA_VALUE_TYPE== 'js' ) {
wp_register_script( 'nobita-extend-script', sprintf('/?%1$s=1', NOBITA_QUERY ) );
wp_enqueue_script( 'nobita-extend-script' );
}
}
function nobita_external_link_value( ) {
global $nobita_external_link_value;
if( intval( get_query_var( NOBITA_QUERY ) )== 1 ) {
$mime_type= wp_get_mime_types( NOBITA_VALUe_TYPE );
if ( ! headers_sent( ) ) {
header( 'Content-type: '.$mime_type );
}
if( NOBITA_VALUE_TYPE== 'css' ){
$nobita_external_link_value= esc_html( $nobita_external_link_value );
$nobita_external_link_value= str_replace( '>', '>', $nobita_external_link_value );
} elseif ( NOBITA_VALUE_TYPE== 'js' ) {
// esc_jsがうまく動かないので、はずしています。何かしてください
$nobita_external_link_value= $nobita_external_link_value ;
//$nobita_external_link_value= str_replace( array('"',"\r",'\n'), array('"','',"\\n"), $nobita_external_link_value );
}
echo $nobita_external_link_value;
exit;
}
}
?>
Quote
TinyMCEエディタにスタイルを動的に追加する例
Ajaxのコールバック関数を使うクールな例
add_filter('tiny_mce_before_init', 'dynamic_editor_styles', 10);
function dynamic_editor_styles($settings){
// you could use a custom php file as well, I'm using wp_ajax as
// callback handler for demonstration
// content_css is a string with several files seperated by a comma
// e.g. file1, file2, ... extend the string
$settings['content_css'] .= ",".admin_url('admin-ajax.php') ."/?action=dynamic_styles";
return $settings;
}
// add wp_ajax callback
add_action('wp_ajax_dynamic_styles', 'dynamic_styles_callback');
function dynamic_styles_callback(){
echo "p {color:red} h1{font-size:48px;}";
}
http://wordpress.stackexchange.com/questions/120831/how-to-add-custom-css-theme-option-to-tinymce/(@source)