dongxie3701 2014-07-24 11:45
浏览 59
已采纳

全局post变量在wordpress插件中不起作用

I understand that the Wordpress global $post may not work until a certain point because it hasnt been loaded, but Im wondering is there a workaround for this.

Basically Im building a plugin specifically for a client. At the moment the variable is showing nothing.

This code is in a plugin in the plugins folder.

Im looking to make sure it only loads javascript (Ive left out that bit) when on specific pages (selected by the user), at the moment its loading on all pages.

My other option is to do it all on a php template, but to be honest I wanted to write it as a plugin with a view to customizing it for more generic use in the future, plus I have little experience with plugins so Im trying to improve that side of things also.

function include_js() {
  global $post;
  print_r($post);

  if(is_object($post) && $post->ID == 14 ){ 
   // do stuff
   wp_enqueue_script('include-map',  plugin_dir_url( __FILE__ ) . 'map.js');
  }
}

add_action( 'init', 'include_js' );

EDIT: I realised my main issue is that I want to include the javascript and because of that I need wp_enqueue_script , but I can only seem to get that work if you use the init action, which happens before the loop.

  • 写回答

3条回答 默认 最新

  • dongshubang7816 2014-07-24 13:17
    关注

    After seeing your edit, try hooking to wp_enqueue_scripts instead of init. Like this:

    function include_js() {
        global $post;
        print_r( $post );
    
        if ( is_object( $post ) && $post->ID == 14 ) { 
            // do stuff
            wp_enqueue_script( 'include-map',  plugin_dir_url( __FILE__ ) . 'map.js' );
        }
    }
    add_action( 'wp_enqueue_scripts', 'include_js' );
    

    Ref: http://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)