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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化