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.
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?
If you want to print something to the head of the document you need use add_action
with wp_head
hook.
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' );
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.
With some minor adjustments to the answer provided by @Jrod, here is the complete working plugin, with usage as follows:
append_css
(or append_js
) with required code<?php
/**
* @package Append_CSS_JS
* @version 0.1
*/
/*
Plugin Name: Append CSS JS
Plugin URI: http://itaccess.org/wordpress-plugins/append-css-js/
Description: Append Css or Js to any page using Custom Fields
Author: Billy Moon
Version: 0.1
Author URI: http://billy.itaccess.org/
*/
function append_css() {
global $post;
if ( ! get_post_meta( $post->ID, 'append_css', true ) ){
return;
}
echo '<style type="text/css">'. get_post_meta($post->ID, 'append_css', true) .'</style>';
}
add_action( 'wp_head', 'append_css' );
function append_js() {
global $post;
if ( ! get_post_meta( $post->ID, 'append_js', true ) ) {
return;
}
echo '<script type="text/javascript">'. get_post_meta($post->ID, 'append_js', true) .'</script>';
}
add_action( 'wp_head', 'append_js' );
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With