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:
Create custom field called append_css (or append_js) with required code
... of course, there is no number 2 ;)
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' );
?>
I don't think this is possible that way, because shortcodes will be called after wp_head(), so you cannot hook on it.
Here's the list of all wordpress hooks http://adambrown.info/p/wp_hooks
EDIT:
Here's a workaround:
In your template:
<?php
//get the content of your post:
if(have_posts()) while(have_posts()) the_post();
$pcontent = get_the_content();
endwhile;
?>
<html>
<head>
...
</head>
<body>
...
<?php echo $pcontent; ?>
</body>
</html>
Related
I'm trying to disable Jetpack Carousel on a specific post ID using the following code in my functions.php
function djcoh_disable_carousel( $value ) {
wp_reset_query();
if ( is_page( 614 ) ) {
$value = true; // true to disable Carousel
}
// Return original or changed value
return $value;
}
add_filter( 'jp_carousel_maybe_disable', 'djcoh_disable_carousel' );
Here's the reference for jp_carousel_maybe_disable on GitHub
It seems that I'm unable to use is_page() within functions.php - though I thought I'd be able to by using wp_reset_query() as mentioned in the codex
What am I missing?!
The code you have is from a tutorial which is intended for running as a simple plugin. The reason your code doesn't currently work is because you are using it in the functions.php.
In it's current form your function is called as soon as it is read as part of the functions.php file. This is usually some time before the page is formed, and so you can't grab the page id with is_page{}.
Instead you should query the page and get it's id as follows:
function djcoh_disable_carousel( $value ) {
//get the global
global $post
echo "TEST PAGE ID: ".$post->ID;
//wp_reset_query();
if ( $post->ID == 614 ) {
$value = true; // true to disable Carousel
}
wp_reset_query();
// Return original or changed value
return $value;
}
add_filter( 'jp_carousel_maybe_disable', 'djcoh_disable_carousel' );
if that doesn't work try this:
function djcoh_disable_carousel( $value ) {
//get the global
global $wp_query;
$post_ID = $wp_query->post->ID;
echo "TEST PAGE ID: ". $post_ID;
//wp_reset_query();
if ( $post_ID == 614 ) {
$value = true; // true to disable Carousel
}
wp_reset_query();
// Return original or changed value
return $value;
}
add_filter( 'jp_carousel_maybe_disable', 'djcoh_disable_carousel' );
If none of the above work then your script is being called far too early in the process to grab the page id. So, the easiest option would be to simply place this script in it's own .php file and then upload that to the plugins root folder. Then activate it from the plugins menu.
The final option would be to create this as a filter or script and add the function call in the actual page template.
I managed this by using REQUEST_URI within a plugin file:
<?php
// No direct access
if ( ! defined( 'ABSPATH' ) ) exit;
if ( $_SERVER["REQUEST_URI"] === '/PAGE-SLUG/' ) {
add_filter( 'jp_carousel_maybe_disable', '__return_true' );
}
Change PAGE-SLUG for your slug and you are all set.
You can find info on REQUEST_URI in PHP's manuals:
'REQUEST_URI'
The URI which was given in order to access this page; for instance, '/index.html'.
It seems simplest to conditionally dequeue the Jetpack carousel script and stylesheet. The conditionals that you would typically use to control output would be available at the point in the request when the wp_footer action fires.
add_action( 'wp_footer', function() {
if ( is_page( $page ) ) {
wp_dequeue_script( 'jetpack-carousel' );
wp_dequeue_style( 'jetpack-carousel' );
}
}
Be certain to modify the is_page function to include the $page parameter or the condition will match all pages. Place the code in your theme's functions.php file and the Jetpack carousel should be disabled.
I try to develop a plugin which includes a file from a template. At this moment my code view is like this:
/* Add a query var for template select, and and endpoint that sets that query var */
add_action( 'init', 'wpse22543_rewrite_system' );
function wpse22543_rewrite_system() {
global $wp, $wp_rewrite;
$wp->add_query_var( 'template' );
add_rewrite_endpoint( 'kalkulator_leasingowy', EP_ROOT );
$wp_rewrite->add_rule( '^/kalkulator_leasingowy/?$',
'index.php?template=kalkulator_leasingowy', 'bottom' );
$wp_rewrite->flush_rules();
}
/* Handle template redirect according the template being queried. */
add_action( 'template_redirect', 'wpse22543_select_template' );
function wpse22543_select_template() {
global $wp;
$template = $wp->query_vars;
if ( array_key_exists( 'template', $template ) &&
'kalkulator_leasingowy' == $template['template'] ) {
global $wp_query;
$wp_query->set( 'is_404', false );
include( get_stylesheet_directory().'/kalkulator_leasingowy.php' );
exit;
}
}
function prefix_movie_rewrite_rule() {
add_rewrite_rule( 'kalkulator_leasingowy', 'index.php?template=kalkulator_leasingowy', 'top' );
}
add_action( 'init', 'prefix_movie_rewrite_rule' );
This code runs very fine and includes the template file, but my template (header.php and footer.php) by default uses a Visual Composer and when I use this code on a page, view this:
Visual Composer works good on all pages without a /kalkulator_leasingowy.
How I can include a VC into /kalkulator_leasingowy as well?
File kalkulator_leasingowy.php
<?php
get_header();
?>
<div class="main-wrapper">
<div class="container ">
<div class="row">
</div>
</div>
</div>
<?php get_footer(); ?>
I'm not really understanding where you are trying to render custom Visual Composer code since your template file doesn't have any in it.
But based on your edit, it looks like you might actually want to be using a child theme. These make it very easy to add new template files to the parent theme without editing any of the parent's code and eliminate the need for most of your complex code.
If perhaps you are injecting the Visual Composer code from somewhere else, make sure you are applying the content filters rather than just inserting or echoing to the front end.
$content = '<div id="my_custom_content">[vc shortcode contents here]</div>';
echo apply_filters('the_content', $content);
This will make sure the end content is filtered and rendered appropriately. You might read this related answer for more information.
I have this PHP script:
function myshortcode_title( ){
return get_the_title();
}
add_shortcode( 'page_title', 'myshortcode_title' );
What is the shortcut i need for the page title to be shown? What do i need to put in the HTML for the fetched title to be shown
Add this to your theme, or make an plugin from it.
/* title to get the post title */
function getPageTitle() {
global $wp_query;
return get_post_title($wp_query->post->ID);
}
/* Add shortcode */
add_shortcode('page_title', 'getPageTitle');
for more ShortCode Api
You may use this.
echo do_shortcode('[page_title]');
https://developer.wordpress.org/reference/functions/do_shortcode/
I have successfully added a content after short description on single product page with
if (!function_exists('my_content')) {
function my_content( $content ) {
$content .= '<div class="custom_content">Custom content!</div>';
return $content;
}
}
add_filter('woocommerce_short_description', 'my_content', 10, 2);
I saw that in short-description.php there was apply_filters( 'woocommerce_short_description', $post->post_excerpt )
so I hooked to that.
In the same way, I'd like to add a content after the add to cart button, so I found do_action( 'woocommerce_before_add_to_cart_button' ), and now I am hooking to woocommerce_before_add_to_cart_button. I'm using
if (!function_exists('my_content_second')) {
function my_content_second( $content ) {
$content .= '<div class="second_content">Other content here!</div>';
return $content;
}
}
add_action('woocommerce_after_add_to_cart_button', 'my_content_second');
But nothing happens. Can I only hook to hooks inside apply_filters? From what I've understood so far by working with hooks is that you only need a hook name to hook to and that's it. The first one was a filter hook, so I used add_filter, and the second one is action hook so I should use add_action, and all should work. So why doesn't it?
Here, you need to echo content as it is add_action hook.
add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart_button_func' );
/*
* Content below "Add to cart" Button.
*/
function add_content_after_addtocart_button_func() {
// Echo content.
echo '<div class="second_content">Other content here!</div>';
}
You need to do echo instead of return.
add_action( 'woocommerce_after_add_to_cart_button', 'ybc_after_add_to_cart_btn' );
function ybc_after_add_to_cart_btn(){
//add text OR HTML here
echo '<p>After custom text here</p>';
}
If you want the same thing on the shop archive page then you need to use the woocommerce_loop_add_to_cart_link filter to modify the add to cart button.
When using 'Action Hook' adding the content(html) out of php would be easy.
if (!function_exists('my_content_second')) {
function my_content_second( $content ) {
?>
<div class="second_content">Other content here!</div>;
<?php
}
}
add_action('woocommerce_after_add_to_cart_button', 'my_content_second');
If need to add dynamic content just echo that content using variables or add using some condition.
Filter hooks are useful to modify the existing content and needs a return statement (the modified)
Action hooks are mostly useful to add content.
I'm new to Wordpress & PHP, so kindly excuse the naivety of the question, if any.
I'm building a plugin where I need to select values from the database and create a new HTML page with the values. I'm using a custom template file.
What I've done till now
Extracted the values from database
Load & display my own template in my plugin file
add_action( 'init', 'leb_add_endpoint' );
function leb_add_endpoint()
{
add_rewrite_endpoint( 'result', EP_PERMALINK );
}
add_action( 'template_include', 'leb_render_template' );
function leb_render_template($default_template) {
//some code removed for brevity
if ( ! is_singular() || !isset($wp_query->query_vars['result']) )
{
return $default_template;
}
$sample_result = $wpdb->get_var($wpdb->prepare($sql));
$default_template = plugin_dir_path(__FILE__) . '/my-custom-template.php';
return $default_template;
}
The content of my-custom-template.php is as follows
<?php
/* Template Name: My Template*/
echo '<h1>Testing</h1>';
?>
The page gets displayed without any problem. All I want is to insert $sample_result and other similar results pulled form database into my-custom-template.php
I need to generate dynamic pages based on values pulled from DB. So each time, the final page created might be different. E.g. if one hits www.example.com/sample-post/result, a page will be shown with values pulled from the DB. If one hits www.example.com/another-sample-post/result, a different page will be shown with different values. Both these pages will have the same design, only a few values will be different. This is what I'm trying to achieve.
How can I do that? Please help me. I'm stuck. :(
You need to define "result" in query vars.
Use EP_ROOT Endpoint Mask ( result/{var} is located in the root )
Inside template_include hook, you can find result value inside $wp_query object.
I've already tested the code
// Add a new var to query vars
function result_add_query_vars( $vars ){
$vars[] = 'result';
return $vars;
}
add_filter( 'query_vars', 'result_add_query_vars' );
// Add endpoint
function result_add_endpoint() {
add_rewrite_endpoint( 'result', EP_ROOT );
}
add_action( 'init', 'result_add_endpoint');
// change the template
function result_render_template($template)
{
global $wp_query;
if ( array_key_exists( 'result', $wp_query->query_vars ) ) {
$result = get_query_var('result');
$new_template = plugin_dir_path(__FILE__) . '/my-custom-template.php';
return $new_template;
} else {
return $template;
}
}
add_action( 'template_include', 'result_render_template' );
Now you can retrieve the query var in your custom template
/*
* Template Name: My Custom Template
*/
$result = get_query_var('result');
echo $result;
Well why don't you use $wp_query Inside your my-custom-template.php
<?php
/* Template Name: My Template*/
global $wp_query;
echo '<pre>';
print_r($wp_query); // Use this in case you want to see what else do you have with you.
echo '<pre/>';
// Now you can use $wp_query to build your dynamic query at run time.
// This will allow you to perform task at run time
?>
To Retrieve Meta
If you have saved something as a meta then
<?php
$meta_values = get_post_meta( $post_id, $key, $single );
?>
To Retrieve Child Post
If you want to retrieve child posts then
<?php
if ( have_posts() ) :
// Start the Loop.
while ( have_posts() ) : the_post();
// Do your stuff here such as below
the_title();
the_content();
endwhile;
else:
echo 'No Post Found';
endif;
?>
1) Write this function in function.php in your active template.
function leb_render_template() {
//some code removed for brevity
//$sql = 'YOUR_QUERY_CODE'
$sample_result = $wpdb->get_var($wpdb->prepare($sql));
return $my_template;
}
add_action('wp_ajax_leb_render_template', 'leb_render_template');
add_action('wp_ajax_nopriv_leb_render_template', 'leb_render_template');
2) Call function in your custom template.
<?php
/* Template Name: My Template*/
echo '<h1>Testing</h1>';
$result = leb_render_template();
print_r($result); // Print Your function output.
?>