create_functionについての質問

このQ&Aのポイント
  • WordPressのテーマで、create_functionを使わずに別の関数を使う方法について質問です。
  • 質問文章のコードを修正して、create_functionを使用せずに関数を定義する方法を教えてください。
  • 公式の指示に従って、create_functionを使用せずにコードを修正する方法について教えていただけますか?
回答を見る
  • ベストアンサー

関数「create_function」について

WordPressのテーマで、下記について質問です。 if($this->options['general']['clean_exerpts']) { add_filter('excerpt_more', create_function('', 'return "";') ); } if($this->options['general']['hide_wp_version']) { add_filter('the_generator', create_function('', 'return "";') ); } create_functionを使わないで別の関数を使いなさいと エラーが表示されるのですが、公式によると function() { // do something }); を使いなさいとあります。 上記PHPコードの場合、 add_filter('the_generator', function() {'', 'return "";'}); ); で合ってますか?教えてください

  • PHP
  • 回答数2
  • ありがとう数3

質問者が選んだベストアンサー

  • ベストアンサー
noname#244856
noname#244856
回答No.2

function hogehoge($value) { ____return "The value is {$value}."; } を無名関数(クロージャ)で表現すると、 function ($value) { ____return "The value is {$value}."; } になります。 これ自体は式なので、 $hogehoge = function ($value) { ____return "The value is {$value}."; }; として変数に代入したり、 変数から使うときは $hogehoge('test'); というようにします。 提示例のように直接 add_filter('the_generator', function () { return ''; }); としてもいいし、分かりにくければ $func = function () { return ''; }; add_filter('the_generator', $func); でも構いません。 なお、create_function関数はPHP5.3以降の環境では絶対に使ってはいけません。 メモリリーク問題を抱えた関数であることで非常に有名です。 PHP5.2以前で使うにしても、こういった使い方をするべきです。 http://bloggdgd.blog28.fc2.com/blog-entry-280.html 無名関数に慣れるとcreate_functionとかゴミすぎて使う気失せますよ・・・(笑

directjpn
質問者

お礼

hogehoge頂きました!!ありがとうございます。 >>無名関数に慣れるとcreate_functionとかゴミすぎて使う気失せますよ HAHAHAHA。ってソレ本当ですか!まだまだ私勉強不足ですなぁ…。 にしても態々コードまでご丁寧に書いて頂きましてありがとうございます。 大変参考になりました。これだからPHPは止められない! 本当に回答ありがとうございました。心より感謝申し上げます

その他の回答 (1)

noname#244856
noname#244856
回答No.1

add_filter('the_generator', function () { return ""; } ); 普通の関数定義から関数名だけ抜けばいいだけ。 http://php.net/manual/ja/functions.anonymous.php

directjpn
質問者

補足

勉強不足で申し訳ありませんが、 「普通の関数定義から関数名を抜く」というのは、 どういう事でしょうか? まだPHPが勉強不足で経験も浅く… もしよろしければ、もう一度回答をお願いいたします

関連するQ&A

  • wordpressでワーニングが出て解決できません

    Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'comments_allow_only_column' not found or invalid function name in C:\xampp\htdocs\wordpress\wp-includes\plugin.php on line 170 ↓plugin.php の170行目の下記の★★部分でエラーが出ているようなのですが PHPの知識がないためどこが悪いのかわかりません。 フォームを設置した部分あたりから全てのページにエラーがでるようになってしまいました。 環境はローカルに設定しています。 $value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args'])); -------------------- function apply_filters($tag, $value) { global $wp_filter, $merged_filters, $wp_current_filter; $args = array(); // Do 'all' actions first if ( isset($wp_filter['all']) ) { $wp_current_filter[] = $tag; $args = func_get_args(); _wp_call_all_hook($args); } if ( !isset($wp_filter[$tag]) ) { if ( isset($wp_filter['all']) ) array_pop($wp_current_filter); return $value; } if ( !isset($wp_filter['all']) ) $wp_current_filter[] = $tag; // Sort if ( !isset( $merged_filters[ $tag ] ) ) { ksort($wp_filter[$tag]); $merged_filters[ $tag ] = true; } reset( $wp_filter[ $tag ] ); if ( empty($args) ) $args = func_get_args(); do { foreach( (array) current($wp_filter[$tag]) as $the_ ) if ( !is_null($the_['function']) ){ $args[1] = $value; ★★$value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args'])); } どの辺を修正すればよいのでしょうか。 宜しくお願い致します。

    • 締切済み
    • PHP
  • WordPressで画像に枠が入ってしまいます。

    WordPressで画像に枠が入ってしまいます。 wordpressでblogを作成しておりますが、画像を投稿したり、img画像を貼り付けるとborderとも違う枠がついてしまいます。 自分で、枠をはずそうと以下の二つを試みましたが解消されません。 1、テーマのstyles.css内に a img {border: 0px;} を追記する 2、テーマのfunction.php内に define('CAPTIONS_OFF', true); add_filter('disable_captions', create_function('','return true;')); を追記する この他に解消する方法はありますでしょうか? もしくは、上記のやり方に謝りがあるのでしょうか? ご存知の方、いらっしゃいましたら、何卒宜しくお願い致します。 該当URL http://www.e-meishin.jp/wordpress/

  • wordpressのadd_action関係

    wordpressステップアップブックという本に載っているとおりに、 function.phpに以下のコードを書きました。 //デフォルトスクリプト function my_scripts() {   if ( is_single() ) {     wp_enqueue_script( 'comment-reply' );   } } add_action( 'wp_enqueue_scripts', 'my_scripts' ); === で、 add_action( 'wp_enqueue_scripts', 'my_scripts' ); を add_action( 'wp_enqueue_scripts2', 'my_scripts' ); に変えても問題なく動きます。 なぜでしょうか? add_action( 'wp_enqueue_scripts', 'my_scripts' ); の第1引数はダミーなのでしょうか? また、1番最初に書いたコードでif文の中にあるwp_enqueue_scriptとadd_action関数の第1関数の役割というか、違いがわかりません。 どなたかお教えいただけないでしょうか? よろしくお願いいたします。

    • ベストアンサー
    • PHP
  • 関数に@を付けて呼び出す

    Wordpressのwp-includes/functions.phpに、この様な記述がありますが、 return @unserialize( $original ); @header( 'X-Content-Type-Options: nosniff' ); 関数に@を付けて呼び出した場合、@を付けない呼び出しとどう違うのでしょうか。

    • ベストアンサー
    • PHP
  • Wordpressでプラグイン内自作関数の有効範囲

    Wordpressでプラグインの作り方を勉強しています。 http://tachibanacw.mond.jp/techwiki/index.php?WordPress%A5%D7%A5%E9%A5%B0%A5%A4%A5%F3%BA%EE%C0%AE このページの中段以降にあるclass ShowTextを作ってみているのですが、このページこう書いてあります。 ※ ただし、footer.phpやheader.php、sidebar.phpでは呼び出し方法(1)は使えない!!! この通りプラグイン内で作った関数を呼び出す <?php echo esc_html($showtext->get_text()); ?> をsingle.phpへ書き込むと正常に表示されますが header.phpやfooter.phpなどでは Call to a member function get_text() on a non-object in C:\xampp\htdocs\~ というエラーが出ます。(ローカルでテストしています) ↑のページには理由が書いてないのですが、これはなぜなのですか? サンプルのソースは以下です。 <?php /* Plugin Name: Show Text Plugin URI: http://localhost/wordpress/plugin Description: テキストを表示するだけのプラグイン Author: A.Hiruta Version: 0.1 Author URI: http://localhost/wordpress */ class ShowText { //「 __construct」はインスタンス化するときに実行されるメソッド function __construct(){ //クラス内のメソッドを指定する場合は第2引数は$thisを含めた配列になる add_action('admin_menu', array($this, 'add_pages')); } function add_pages(){ add_menu_page('テキスト設定','テキスト設定', 'level_8', __FILE__, array($this, 'show_text_option_page'), '', 26); } function show_text_option_page() { //$_POST['showtext_options'])があったら保存 if ( isset($_POST['showtext_options'])) { check_admin_referer('shoptions'); $opt = $_POST['showtext_options']; update_option('showtext_options', $opt); ?><div class="updated fade"><p><strong><?php _e('Options saved.'); ?></strong></p></div><?php } ?> <div class="wrap"> <div id="icon-options-general" class="icon32"><br /></div><h2>テキスト設定</h2> <form action="" method="post"> <?php wp_nonce_field('shoptions'); $opt = get_option('showtext_options'); $show_text = isset($opt['text']) ? $opt['text']: null; ?> <table class="form-table"> <tr valign="top"> <th scope="row"><label for="inputtext">テキスト</label></th> <td><input name="showtext_options[text]" type="text" id="inputtext" value="<?php echo $show_text ?>" class="regular-text" /></td> </tr> </table> <p class="submit"><input type="submit" name="Submit" class="button-primary" value="変更を保存" /></p> </form> <!-- /.wrap --></div> <?php } //何故かfooter.phpにはecho esc_html($showtext->get_text());を記述してもダメだった。 function get_text() { $opt = get_option('showtext_options'); return isset($opt['text']) ? $opt['text']: 'null desu.'; } } //クラスを記述して、その場でインスタンス化(実行) $showtext = new ShowText; ?> よろしくおねがいいたします。

    • ベストアンサー
    • PHP
  • jQueryを利用したアコーディオンメニュー

    wordpress上でjQueryを使用したアコーディオンメニューを作成しようと思います。 サイトの左カラムに設置して、ボックス化されたリストの一部をクリックするとメニューの開閉、 テキストリンクの部分をクリックするとカテゴリのリンクに飛ぶように作成したいと考えております。 アコーディオンの開閉までは作成できたのですが、そこからカテゴリへのリンクがうまく行きません。。 javascriptがあまり詳しくないので、ぜひともお力を貸してください。 よろしくお願いします。 <!--javascript--> <script type="text/javascript"> var j$ = jQuery; j$(function(){ j$(".acc").each(function(){ j$("li < a", this).each(function(index){ var $this = j$(this); if(index > 0) $this.next().hide(); $this.click(function(){ var params = {height:"toggle", opacity:"toggle"}; j$(this).next().animate(params).parent().siblings() .children("ul:visible").animate(params); return false; }); }); }); }); </script> <!--/javascript--> <!--php--> <ul class="acc"> <?php wp_list_categories('hide_empty=0&title_li='); ?> </ul> <!--/php-->

  • プログラム無知の者です。

    プログラム無知の者です。 jQueryのアコーディオンメニューで開いたメニューをマウスを外しても開いたままにしたいのですが、 どこをいじればいいかわかりません。 var j$ = jQuery; j$(function(){ j$(".acc").each(function(){ j$("li > a", this).each(function(index){ var $this = j$(this); if(index > 0) $this.next().hide('normal'); $this.mouseover(function(){ j$(this).next().show('normal').parent().siblings() .children("ul:visible").hide('normal'); return false; }); }); }); }); 初歩的な質問で申し訳ないですが、どうぞよろしくご指導お願いします。

  • function validateFormについて

    ショッピングサイトを制作しているWebデザイナーです。Java Scriptのfunction validateFormについて質問です。 商品をショッピングカートに入れる際、FormのsubmitでサーバーのASPにデータを受け渡す仕組みで、ユーザーがsubmitボタンをクリックした際、商品の選択項目(select)が選択されていないとエラーメッセージが出るようにしています。 選択項目(select name)は「Color」と「Size」とありますが、現在、エラーメッセージ用のJava Scriptを、 「ColorとSize両方チェック」 function validateForm() { //--------------------------------------------------- if (document.form1.Size.options.value == 'Error') { alert('Please select Size !') document.form1.Size.focus() return false } if (document.form1.Color.options.value == 'Error') { alert('Please select Color !') document.form1.Color.focus() return false } } 「Colorのみチェック」 function validateForm() { //--------------------------------------------------- if (document.form1.Color.options.value == 'Error') { alert('Please select Color !') document.form1.Color.focus() return false } } と2つ使い分けています。 この2つをひとつのファイル(.js)にまとめることはできますか?また、今後また新たな選択項目が出てきた時、ファイル(.js)を増やすのではなく、scriptの中身を追加して対応させていきたいのですが、そうするにはjava scriptをどのように記述すればいいでしょうか? 分かる方、教えてください。 よろしくお願いします。

  • PHPで定義されるあるクラスの関数について

    お世話になります。自分がいま勉強しているPHP教本の中の、画像ファイルをアップロードするクラスUploadを以下に掲載します。 自分の質問は この中のcheckFile()という関数についてです。 それぞれがtrueまたはfalseを返す3つの関数を続けて実行していますが、すべての戻り値がtrueでなければtrueを返せないはずなのに、ここでは一番最後のcheckType()がtrueであれば前の2つはfalseでも構わないことになってしまいます。それぞれの戻り値である$accept を順次かけ合わせていけば問題ないように思われますが、そうではなくて、それぞれを単純に$accept に代入するだけでよいのでしょうか? 詳しい方、どうかご意見をお聞かせください。 class Upload{ protected $destination; protected $max = 81920; protected $messages = [];// error or success message, to show to the user protected $permitted = ['image/gif', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/webp' ]; // to check if the uploaded file is one of these types public function __construct($path){ if(is_dir($path) && is_writable($path)){ $this->destination = rtrim($path, '/\\').DIRECTORY_SEPARATOR; }else{ throw new \Exception("$path must be a valid, writable directory.") } } public function upload($fieldname){ $uploaded = $_FILES[$fieldname]; if($this->checkFile($uploaded)){ // child function 1 $this->moveFile($uploaded); // child function 2 } } protected function checkFile($file){ // child function 1 $accept = $this->getErrorLevel($file); $accept = $this->checkSize($file); $accept = $this->checkType($file); return $accept; } protected function moveFile($file){ // $file is the same as $uploaded in parent function $success = move_uploaded_file($file['tmp_name'], $this->destination.$file['name']); if($success){ $result = $file['name'] .' was uploaded successfully.'; $this->messages[] = $result; }else{ $this->messages[] = 'Could not upload '.$file['name']; } } public function getMessages(){ return $this->messages; } protected function getErrorLevel($file){ switch($file['error']){ case 0: return true; case 1: case 2: $this->messages[] = $file['name'].' is too big. (max: '.$this->getMaxSize().')'; break; case 3: $this->messages[] = $file['name'].' was only partially uploaded.'; break; case 4: $this->messages[] = 'No file was submitted.'; break; default: $this->messages[] = 'Sorry. There was a problem uploading '.$file['name']; } return false; } protected function checkSize($file){ if($file['error'] == 1 || $file['error'] == 2 ){ return false; }else if($file['size'] == 0){ $this->messages[] = $file['name']. " is an empty file."; return false; }else if($file['size']>$this->max){ $this->messages[] = $file['name']." exceeds the maximum size for a file (". $this->getMaxSize().")"; return false; } return true; } protected function checkType($file){ if(!in_array($file['type'], $this->permitted)){ $this->messages[] = $file['name']." is not permitted type of file."; return false; } return true; } public function getMaxSize(){ return number_format($this->max/1024, 1)." KB"; } }

    • ベストアンサー
    • PHP
  • jQueryで6行表示のループ

    大雑把な質問なのですが、自分でもわかっているのですが、 もっと簡単なやり方がないものかと色々とやっていたのですが、 ありませんでしょうか? $(document).ready(function() { var nCnt2 = 1; var nMax2 = 6; if(nMax2 < $('ul#portfolio li').length) { $('ul#portfolio li').hide('fast').addClass('hidden'); $('ul#portfolio li.hidden').hide('fast').addClass('hidden'); $('ul#portfolio li.hidden').each(function() { if(nCnt2 <= nMax2) { $(this).fadeIn('slow').removeClass('hidden'); } nCnt2++; }); } $('ul#navi a').click(function() { $(this).css('outline','none'); $('ul#navi .all').removeClass('current'); $(this).parent().addClass('current'); var filterVal = $(this).text().toLowerCase().replace(' ','-'); var nCnt = 1; var nMax = 6; if(filterVal == 'all') { $('ul#portfolio li').hide('fast').addClass('hidden'); $('ul#portfolio li.hidden').hide('fast').addClass('hidden'); $('ul#portfolio li.hidden').each(function() { if(nCnt <= nMax) { $(this).fadeIn('slow').removeClass('hidden'); } nCnt++; }); } else { $('ul#portfolio li').hide('fast').addClass('hidden'); $('ul#portfolio li').each(function() { if(!$(this).hasClass(filterVal)) { $(this).fadeOut('normal').addClass('hidden'); } else if (nCnt <= nMax) { $(this).fadeIn('slow').removeClass('hidden'); nCnt++; } }); } return false; }); });

専門家に質問してみよう