LoginSignup
3
0

More than 5 years have passed since last update.

WordPressのアクションフックで無名関数に引数を渡す

Posted at

はじめに

WordPressのアクションフックに引数を渡したい、という場面がありました。

add_action('wp_footer', function() use ($arg) {
 echo $arg;
});

無名関数 | PHP.net
http://php.net/manual/ja/functions.anonymous.php

どこで欲しかったの?

JavaScriptの操作周りだったのでフッターで出力する必要があり、アクションフック登録時に引数を渡したいと思いました。

カスタム投稿タイプの出力周りをsingle-cpt.phpで簡潔させることができました。

店舗というカスタム投稿タイプについて、フッターで地図情報をカスタムフィールドから取得して出力させたかった。
JavaScriptのグローバル変数でHTML中に記述してもよかったんだけれど、フッター付近に集めたかったです。

public function theMap() {
    $geo = get_field('geo');
    add_action('wp_footer', function() use ($geo) {
        ?>
        <script>
            jQuery(document).ready(function() {
                var latlng = new google.maps.LatLng(<?php echo $geo['lat']; ?>, <?php echo $geo['lng']; ?>);
                var myOptions = {
                    zoom: 20, /*拡大比率*/
                    center: latlng, /*表示枠内の中心点*/
                    mapTypeId: google.maps.MapTypeId.ROADMAP, /*表示タイプの指定*/
                    draggable: false,
                    scrollwheel: false
                };
                var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
                var marker = new google.maps.Marker({
                    position: latlng,
                    map: map
                });
                });
        </script>
        <?php
    });
}
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0