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条)

报告相同问题?

悬赏问题

  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题