following the tutorial at http://josephscott.org/archives/2010/03/database-powered-css-in-wordpress-themes/ i am trying to use wordpress' parse_request function to add some php-driven CSS... mostly style options set in my theme's options panel. i am aware that my code looks a little different from the author's, but i tried it his way already. i can add the
function kia_wp_head() {
wp_enqueue_style('dynamic', get_bloginfo('stylesheet_directory') . '/admin/ . '?my-custom-content=css');
}
add_action('wp_print_styles', 'kia_wp_head');
//this shows up properly enqueued but when i click on it in source it just brings up a directory listing for the admin folder
function my_custom_wp_request( $wp ) {
if( isset($_GET['my-custom-content']) && $_GET['my-custom-content'] == 'css' ) {
# get theme options
header( 'Content-Type: text/css' ); ?>
body {
background-color: <?php echo 'red'; ?>
}
<?php
exit;
}
}
add_action( 'parse_request', 'my_custom_wp_request' );
but since the background never turns red, I am either not implementing this properly or the tutorial is missing a critical step. i've also tried the other method of putting the dynamic css in its own custom-css.php file, which is my ultimate goale, but i was just trying to see if i could interact with the parse request function properly:
function my_custom_wp_request( $wp ) {
if (
isset($_GET['my-custom-content'])
&& $_GET['my-custom-content'] == 'css'
) {
# get theme options
header( 'Content-Type: text/css' );
require dirname( __FILE__ ) . '/custom-css.php';
exit;
}
}
add_action( 'parse_request', 'my_custom_wp_request' );
here i'm not sure what dirname( FILE ) means exactly, but i have also tried using a hardcoded path and that didn't work either.
so how do i get parse_request to see my php-driven stylesheet?
/* EDIT FOR SOLUTION */
basically this doesn't work w/ wp_enqueue_style
wp_enqueue_style('dynamic', get_bloginfo('stylesheet_directory') . '/admin/ . '?my-custom-content=css');
but DOES work as described at josephscott.org by inserting the style tag directly into the head
. '/admin?my-custom-content=css">
i found that it doesn’t work w/ wp_enqueue_script. it does work as written in the tutorial by manually adding the script tag to the header.
Related
I would like to change the logo redirection when clicked. Right now when you click on the logo, the user is redirected to the homepage but I want it to redirect to another site. How do I do this?
I agree with Stu Mileham. Another way to implement what you are asking for would be to use JavaScript / jQuery.
Save the following code to a .js file (eg. pageRedirect.js, let's say placed in a js folder inside your theme's root folder):
(function($) {
$(document).ready(function() {
$('#pageLogo').on( "click", function(event) {
event.preventDefault();
window.location.assign("http://www.google.com/");
});
});
})(jQuery);
To make the previous code work, you would have to select somehow the page logo via jQuery.
On the previous code this is achived via $('#pageLogo') since I have made the assumption that your logo has an id with the value pageLogo.
Of course, to enable your theme to use this pageRedirect.js file, you have to enqueue it by placing the following code to your theme's functions.php file:
/**
* Enqueue pageRedirect script.
*/
function pageRedirect_scripts() {
wp_enqueue_script( 'page-redirect-js', get_template_directory_uri() . '/js/pageRedirect.js', array('jquery'), '20150528', true );
}
add_action( 'wp_enqueue_scripts', 'pageRedirect_scripts' );
Code Explanation:
//-jQuery selects html element with id='pageLogo'
//-when it is clicked, it calls a function in which it passes the event
$('#pageLogo').on( "click", function(event) {
//prevents page from redirecting to homepage
event.preventDefault();
//redirects to your desired webpage
window.location.assign("http://www.google.com/");
});
If you don't have the option to change the link from admin then you will have to edit your theme's header.php file (most likely, depends on how the theme is built though).
Many themes have a tag similar to the following:
<img src="logo.jpg">
You would need to change this to:
<img src="logo.jpg">
I've added the target tag to open the site in a new window, this is my personal preference when re-directing to a different site but it's optional.
Your theme files might look very different to this, it's impossible to know for sure without seeing some code, but this should give you an idea.
Also be aware that your changes could be overwritten by a theme update. This can be avoided by creating a child theme.
https://codex.wordpress.org/Child_Themes
Depends on your theme
Some theme creators gives you the possibility to change the link from admin
Some theme creators just believe that clicking the logo you need to go on homepage - so you need to edit the theme
Depending upon the theme you are using, you can try one of the following options.
Explore the admin options and see if the theme provides a direct way to change the link on the logo.
If not found in admin options, try looking for the code in header.php. Do an inspect element on your logo and see the html code surrounding the logo file, If the code is directly present in header.php, your task is simple. Just change the code to update the URL, instead of reading it from home_url(). Something like <a href="<?php echo home_url();?>"> will need to be replaced with <a href="https://www.example.com">
The other option to look for is get_custom_logo. Some themes get the logo code from this function. You can apply a filter to change the home_url just before this method is called in your theme and then remove filter afterwards. Or else you can copy the code from wordpress and update it with a differently named function say get_custom_link_logo in functions.php then where'ver your theme is using get_custom_logo you can use get_custom_link_logo instead of that.
function get_custom_link_logo ( $blog_id = 0 ) {
$html = "";
$switched_blog = false;
if ( is_multisite() && ! empty( $blog_id ) && (int) $blog_id !== get_current_blog_id() ) {
switch_to_blog( $blog_id );
$switched_blog = true;
}
$custom_logo_id = get_theme_mod( 'custom_logo' );
// We have a logo. Logo is go.
if ( $custom_logo_id ) {
$custom_logo_attr = array(
'class' => 'custom-logo',
'itemprop' => 'logo',
);
/*
* If the logo alt attribute is empty, get the site title and explicitly
* pass it to the attributes used by wp_get_attachment_image().
*/
$image_alt = get_post_meta( $custom_logo_id, '_wp_attachment_image_alt', true );
if ( empty( $image_alt ) ) {
$custom_logo_attr['alt'] = get_bloginfo( 'name', 'display' );
}
/*
* If the alt attribute is not empty, there's no need to explicitly pass
* it because wp_get_attachment_image() already adds the alt attribute.
*/
$html = sprintf( '%2$s',
esc_url( "https://www.example.com" ),
wp_get_attachment_image( $custom_logo_id, 'full', false, $custom_logo_attr )
);
}
// If no logo is set but we're in the Customizer, leave a placeholder (needed for the live preview).
elseif ( is_customize_preview() ) {
$html = sprintf( '<img class="custom-logo"/>',
esc_url( "https://www.example.com" )
);
}
if ( $switched_blog ) {
restore_current_blog();
}
/**
* Filters the custom logo output.
*
* #since 4.5.0
* #since 4.6.0 Added the `$blog_id` parameter.
*
* #param string $html Custom logo HTML output.
* #param int $blog_id ID of the blog to get the custom logo for.
*/
return apply_filters( 'get_custom_logo', $html, $blog_id ); }
This might not cover all the use cases, but you get the idea. Depending upon the theme you'll have a similar solution for your case. The important thing to figure out which case you fall under will be to identify the code where html for your logo is getting added. header.php is a good starting point.
Use this javascript in the header or footer of your theme:
<script>
document.getElementsByClassName("site-logo")[0].getElementsByTagName('a')[0].href="https://www.test.com";
</script>
i am assuming that site-logo is the class name of your LOGO.
I'm trying to do a plugin that will change the behavior of a theme.
In the theme file I have a get_template_part('libs/templates/user_menu');
I want to make my plugin to "force" the get_template_part return another slug file (a path to a file in plugin folder).
So far this is my code inside the plugin:
function wpse21352_template_part_cb( $slug )
{
if(slug == 'user_menu') {
return WP_PLUGIN_URL.'/'.$slug;
} else {
return $slug;
}
}
do_action( "get_template_part_user_menu", 'user_menu' );
add_action( 'wpse21352_template_part_cb', 'get_template_part_user_menu', 10, 1 );
First of all, get_template_part does not return anything. It loads a file from your theme based on the parameters you pass to it. The function does not support filtering, which means you can not actually overwrite what is outputted by get_template_part.
The only thing the action get_template_part_[slug] allows you to do is output something before the theme file is loaded. For example, using
function myplugin_before_login( $slug, $name ) {
echo 'Example';
}
add_action( 'get_template_part_login', 'myplugin_before_login', 10, 2 );
would output "Example" before the loading the theme file when calling get_template_part( 'login' );.
Actions and filters
In general, however, I believe you might misunderstand how actions and filters work. The WordPress Codex offers extensive information on their use and usage.
I enqueue a bunch of scripts into the footer of my page:
function core_scripts() {
wp_deregister_script('jquery');
wp_register_script('jquery', '//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js', false, null, true);
wp_register_script('bootstrap', '//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js', array('jquery'), '3.1.1', true);
wp_register_script('flexslider', get_template_directory_uri().'/js/jquery.flexslider-min.js', array('jquery'), '2.2.2', true);
wp_register_script('jqzoom', get_template_directory_uri().'/js/jquery.jqzoom-core-pack.js', array('jquery'), '2.3', true);
wp_register_script('fancybox', get_template_directory_uri().'/js/jquery.fancybox.pack.js', array('jquery'), '2.1.5', true);
... a bunch of others ...
}
add_action('init', 'core_scripts'); // Add Custom Scripts
function write_site_scripts()
{
wp_enqueue_script('jquery');
wp_enqueue_script('bootstrap');
wp_enqueue_script('flexslider');
wp_enqueue_script('jqzoom');
wp_enqueue_script('fancybox');
...etc...
}
add_action('wp_enqueue_scripts', 'write_site_scripts'); // write all enqueued scripts
function write_custom_scripts()
{
$html = "<!-- Custom script -->
<script>
var custom = '1';
</script>";
echo $html;
}
add_action('wp_footer', 'write_custom_scripts'); // this script writes in the footer before the dependent js scripts
My problem is that the custom script is always written to the page before the jQuery scripts, I guess because the custom script is written to the page via an echo write command.
How can I add custom javascript code into the footer after the jQuery scripts have been written to the page? ie. I need to delay the add_action('wp_footer', 'write_custom_scripts'); to be executed at a later moment, or how can I use enqueue to add a custom javascript?
Note I have removed the CDN code posted earlier since this leads everyone into another discussion - a valid one, but it's not the issue I am after at this moment.
Edit II
Since the question has changed in essence many times, and In order to save you from reading ( e.g. - understanding ) all of the long explanation below, just use .
add_action('wp_footer', 'write_custom_scripts',9999);
This will set the priority to very high and will probably echo your code last ( unless you or other plugin / theme developers used a higher priority or later filter ..)
For those who want to do the right way :
function my_javascripts() {
wp_enqueue_script('the-script-handle',
'path/to/file.js',
array('jquery','other_script_that_we_depend_on'),
'scriptversion eg. 1.0',
true);
}
add_action('wp_enqueue_scripts', 'my_javascripts');
When you enqueue a script like above ( the right way ) , you can see that it wp_enqueue_script() has 4 arguments.path, dependencies ,version ,and in-footer .
This is the only right way to load a script , and if you need , just enqueue also jquery at the same function -- wp will make sure it loads first .
The dependencies means that wp will not load your script UNLESS jQuery is already loaded and will try to load jQuery FIRST ...
The LAST argument will actually define weather to load your script in the FOOTER ( TRUE ) or in header ( FALSE )
That being said , you can always load jQuery in the HEADER and not footer ( but it is not so recommended )
After that , For the last bit of your script , you can echo it in the footer , and you can also control how and when to add it .
What I do not understand , is the overall aim of your method . ( this part is about the "doing it wrong " )
Firstly - I think that loading from CDN is not a good IDEA . AND I AM NOT ALONE. it is to be considered a bad practice in WP without any meaningful Pros ( the time issue is a joke since you will be probably loading a LOT of other scripts directly AND scripts are Cached ).
While doing it - it is good that you think of a fallback, but the fallback should be wp own version - and not one that you include yourself .
If you still insist on doing it wrong , you can always do something like ( or just change order of execution ):
remove_action('wp_head', 'wp_print_scripts');
remove_action('wp_head', 'wp_print_footer_scripts', 9);
remove_action('wp_head', 'wp_enqueue_scripts', 1);
// your stuff
add_action('wp_footer', 'wp_print_scripts', 5);
add_action('wp_footer', 'wp_enqueue_scripts', 5);
add_action('wp_footer', 'wp_print_footer_scripts', 5);
Which basically allow you to echo your stuff before or after the wp_footer action at will And while technically it will work -. it is still wrong .
Edit I After question edit .
you have several problems in that code .
you are registering jQuery (CDN ) with the handle jquery which is reserved for WP.
If you want to do that ( and you shouldn´t . please don´t ) you need to deregister jquery BEFORE registering it again .
<?php wp_deregister_script( 'jquery' ); ?>
Again. I can not stress enough how wrong that is .
2 . you are registring the whole bunch of script - but where do you enqueue them ?
3 . Again . Like in comments ( I think you still do not understand )
If you have a script to add to the footer - you need to register and enqueue it with dependencies .. ( the right way )
In your case from edited question :
make a file called my_script.js
var custom = '1';
Enqueue it !
wp_enqueue_script('the-script-handle',
'path/to/my_script.js',
array('jquery','other_script_that_we_depend_on'),
'0.0.1',
true);
In this case , your script will load AFTER the dependencies you listed ...
What you are trying to do is echoing directly .
As for the comment of how to correctly pass variables - read here
And you can also do something like this ( objects ):
$data = (object) array(
'render' => 'canvas',
'size' => 100,
'radius' => ($q_corner_r * 0.3),
);
$output .=
<script type="text/javascript">;
//<![CDATA[
var options = ' . json_encode($data) . '
// ]]>;
</script>';
I want my plugin to register a script only in a certain page.
For example, inside my plugin file I want to write something like this:
if (is_page()) {
$pageid_current = get_the_ID();
$page_slug = get_post($pageid_current)->post_name;
if ($page_slug == 'articles'){
wp_register_script('myscript', '/someurl/main.js');
}
}
But I get the error:
is_page was called incorrectly. Conditional query tags do not work
before the query is run. Before then, they always return false. Please
see Debugging in WordPress for more information. (This message was
added in version 3.1.)
How can I, inside of a plugin, register a script in a certain page?
is_page() only work within template files.
And to use it within plugin files, you need to use it with the combination of template_redirect action hook.
This action hook executes just before WordPress determines which template page to load.
So following snippet would work:
add_action( 'template_redirect', 'plugin_is_page' );
function plugin_is_page() {
if ( is_page( 'articles' ) ) {
wp_register_script( 'my-js-handler', '/someurl/main.js', [], '1.0.0', true );
}
}
You could use is_page() after template redirect so you need to add in the hook like this :
add_action('template_redirect','your_function');
function your_function(){
if ( is_page('test') ) {
// do you thing.
}
}
You must register your script as if you want it to work everywhere.
You can de-register it after the job is done, like this:
function deregister_my_script() {
if (!is_page('page-d-exemple') ) {
wp_deregister_script( 'custom-script-1' );
}
}
add_action('wp_print_scripts', 'deregister_my_script', 100 );
I have been looking for an answer for this in SOF but didn't find a clear answer
I have a plugin that forces pages to be shown when certain conditions are met. but when i try to include css files for styling i get no response .
I tried to include the file using normal html and this was a failure
then tried the wp_register_style and wp_enqueue_style as such:
function rw_add_style(){
$rw_path = plugins_url('kawaleb/style.css');
wp_register_style('testili',plugins_url('kawaleb/style.css'));
wp_enqueue_style( 'testili' );
}
add_action ('wp_enqueue_scripts','rw_add_style');
wp_enqueue_style( 'testili' );
}
I placed this code on the page that should be shown when the conditions are met
What I don't know here is how to procede after enqueing !
do I need to use html to include the stylesheet file ( and then what is the use of enqueing ?) or does it do that by itself (and then what I am missing here ? )
In the doc of codex they dont go further than telling you to register the style then enqueue it !!!
Thank you all :)
You don't need to register the style, you can just enqueue it. Also, you mentioned that you've put the code in the file where you'd like it to display, you should put it in the index file of your plugin, so in /your-plugin/index.php or whatever the main file is called, add this code:
function rw_add_style() {
wp_enqueue_style( 'testili', plugins_url( 'kawaleb/style.css' ) );
}
add_action( 'wp_enqueue_scripts', 'rw_add_style' );
If you need it only on a certain page then you should add your conditional within the function, so you could do this for example:
function rw_add_style() {
global $post;
if ( $post->post_name == 'post_name' ) {
wp_enqueue_style( 'testili', plugins_url( 'kawaleb/style.css' ) );
}
}
add_action( 'wp_enqueue_scripts', 'rw_add_style' );
And you can work out what the post name is for the page you need to enqueue it for by temporarily adding the following code to the page template:
global $post;
echo $post->post_name;
To be clear, you don't need to add any html <link> to include the CSS as you're right, there would be no point in enqueuing it then. Just add the enqueue as I described above in the main index file of your plugin and it will be automatically included in the wp_head() in your header and output just before the </head>.
I hope this helps. Good luck. =)