Wordpress 从短代码回调中附加到 HEAD [英] Wordpress append to HEAD from within shortcode callback

查看:29
本文介绍了Wordpress 从短代码回调中附加到 HEAD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个插件来注册一个短代码,当像这样使用时:[append_css mycss] 它将寻找一个名为 mycss 的自定义字段并添加内容到文档的head.一切都很好,除了代码被添加到正文中,我不知道如何让它添加到头部.

I am making a plugin, to register a shortcode, which when used like this: [append_css mycss] it will look for a custom field called mycss and add the contents to the head of the document. It all works great, except that the code is being added to the body, and I don't know how to get it to add to the head.

我尝试添加一个动作 wp_head,但我不知道如何在执行此操作时传递变量,而且它似乎并没有从短代码回调中触发.

I have tried adding an action wp_head but I don't know how to pass variables whilst doing that, and it does not seem to fire from within the shortcode callback anyway.

function append_css_short($params){
  global $post;
  if(sizeof($params)){
    $key = $params[0];
  } else {
    $key = 'css';
  }
  return '<style type="text/css">'.
  get_post_meta($post->ID, $key, true)
  .'</style>';
}
add_shortcode('append_css','append_css_short');

我如何让这个写入头部而不是身体?有没有更好的方法来解决这个问题?

How would I get this to write to the head instead of body? Is there a better approach to the problem?

推荐答案

如果你想打印一些东西到文档的头部,你需要使用 add_actionwp_head 钩子.

If you want to print something to the head of the document you need use add_action with wp_head hook.

更好的方法可能是根本不使用短代码.短代码旨在添加内容或修改内容.而是创建一个可以附加到 wp_head 的函数,该函数将打印您的 css.您可能希望强制用户保持自定义字段名称一致.或者更好的是让您的插件向帖子添加一个元框,他们可以在其中输入自定义 css.这样您就可以始终确定该字段的名称.

A better approach might be to not use a shortcode at all. Shortcodes are intended to add content or modify content. Instead create a function that you can attach to wp_head that will print your css. You may want to force the user to keep the custom field name consistent. Or better yet have your plugin add a metabox to posts that they can enter custom css into. Then you will always be certain of the name of the field.

function append_css() {

   global $post;

   if ( ! get_post_meta( $post->ID, 'mypluginname_css', true ) ) {
      return;
   }

   return '<style type="text/css">'. get_post_meta($post->ID, $key, true) .'</style>';

}

add_action( 'wp_head', 'append_css' );

我唯一不确定的是带有自定义字段数据的 $post 是否在循环外可用.因此,您可能需要在其中添加一些额外的查询,以在触发 wp_head 时提取自定义数据.

The only thing i am not certain of is whether or not $post with the custom field data will be available outside the loop. So you may have to add some extra querying in there to pull the custom data at the time that wp_head is fired.

这篇关于Wordpress 从短代码回调中附加到 HEAD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆