How I can add my JQuery script into single wordpress page? - wordpress

I want to add my JQuery script into single Wordpress page, but I dont know how. Example of script I'd like to inject:
<script type="text/javascript">
$(document).ready(function() {
$("html, body").animate({ scrollTop: $(window).height() }, 600);
return false;
});
</script>
This code works fine when injected in plain HTML, but how can I do the same for Wordpress?

Personally I feel the best way for adding a JavaScript to a particular page/post is to use ShortCode
Add this:
function add_my_script() {
return "<script>
//your jQuery here
</script>";
}
add_shortcode( 'myCustomShortCode', 'add_my_script' );
to your function.php file. Your function.php file is location at /wp-content/themes/<name of theme>/
NOTE: Use ' instead of " in your <script> to continue inside the return statement.
Now simply add the shortcode [myCustomShortCode] in your page.

you have a couple of options, the function you created above will add it to all pages (you were registering the script but not actually calling it, thats why its not working. see correction below).
If you want you can simply place the wp_enqueue_script() function below in your template (without add action and the custom() function
or directly write it into the template file (lots of arguments about whether this is acceptable coding practice, but it works)
or require_once / include_once the file in the correct sequence (you are using document.ready so you can do this anywhere below the header (if you already have jquery loaded in the header, if in the footer, must be below the footer) same rules apply for directly writing into the file.
function custom() {
wp_enqueue_script('jquery');
wp_enqueue_script('add-custom-js' , get_template_directory_uri() . '/js/custom.js' , array('jquery'),'',true );
}
add_action('wp_enqueue_scripts' . 'custom' );
also WP uses non conflict jquery so you need to use jQuery instead of the the shorthand vers $. there are a few alternative ways to use the shorthand if you google it.

just edit a page in wordpress, select text view (not formatted text) and paste your script wherever you like.

Related

Where to put javascript function in wordpress to apply to side navigation

I have the following code to initially hide sub navigation of a sidebar menu in wordpress:
$(document).ready(function() {
$(".children").hide();
$("#menu-item").click(function() {
$('.children').slideToggle('medium');
});
});
I have it working correctly in jsfiddle(http://jsfiddle.net/MLUb8/), but can't get it working in wordpress. Where should it be placed within my theme for this to work? I've tried the header.php, footer.php and template file.
You should put the code in a separate file and include it using wp_enqueue_script (the value for $deps should be array( 'jquery' ):
http://codex.wordpress.org/Function_Reference/wp_enqueue_script
Additionally, WordPress uses noconflict, so you should slightly modify your code, like so:
jQuery(document).ready(function($) {
$(".children").hide();
$("#menu-item").click(function() {
$('.children').slideToggle('medium');
});
});
It actually worked directly within the template file itself. No need to embed from a separate file.

Add wp_header depending on wp_content in Wordpress Plugin

I am developing a Wordpress plugin to run a certain javascript function based on some parameters.
The first step is to include the javascript file from my server. Easy:
add_action('wp_head', 'my_plugin_head');
function my_plugin_head(){
echo '<script type="text/javascript" src="http://www.my-server.net/js/w.js" ></script>';
}
The second step is to change certain text in the WordPress body to the javascript function...something like:
add_filter('the_content', 'plugin_text_replace');
function plugin_text_replace($text){
$text=preg_replace('blah', 'blah');
return $text;
//I Am still researching how to setup the preg_replace.
//It will look for something like plugin_call[1, 40, 60]
//And Change it To jsFunction(1, 40, 60);
//Bonus for anyone who can help me with that :)
}
In any case, I realized that I want the my-server.net javascript included ONLY if needed (or in other words, only if the preg_replace found a match). This is problematic to me because I can't find anyway to add a script to the <head> tag without using an action on wp_head, which does not have any reference to the body of the text.
How can I add a header ONLY if a certain preg_match is found?
To add javascript the best way is using wp_enqueue_script(), like this:
function my_scripts_method() {
wp_enqueue_script('my_java_function');
}
// For use on the Front end (ie. Theme)
add_action('wp_enqueue_scripts', 'my_scripts_method');
Inserting code into the <body> can be achieved like this:
function wp_body() {
do_action( 'wp_body' );
}
add_action( 'wp_body', 'my_body_function' ) ; //
// In "header.php" place something like this after <body>:
if ( function_exists('wp_body')) wp_body(); ?>

Make Wordpress Pages's Titles readonly

I'm looking for a WP function that add the Read-only parameter to all Pages's Titles's input, that will make the Page's title unalterable.
Thanks a lot in advance.
This can be accomplished with some simple JavaScript/jQuery. Create a file called admin_title_disable.js, and queue it up within functions.php. For example:
functions.php:
wp_register_script('admin_title_disable', '/path/to/admin_title_disable.js');
function disableAdminTitle () {
wp_enqueue_script('admin_title_disable');
}
add_action('admin_enqueue_scripts', 'disableAdminTitle');
Now, in your js file:
jQuery(document).ready(function ($) {
$('#title').attr('disabled','disabled');
});
This will set both post and page title input fields with a disabled attribute. Hope this helps!
If you want to restrict this script to a particular admin page, wrap the add_action hook in a conditional that compares $_GET['page']. You can also take advantage of the $hook parameter that is available when using admin_enqueue_scripts to check for the page. See here.
Update::
WordPress makes it a little tricky to tell between post and page edit screens, but there is a hidden input that you can take advantage of. :) Here's an updated version of the jQuery that will only run on page edit screens:
jQuery(document).ready(function ($) {
//find the hidden post type input, and grab the value
if($('#post_type').val() === 'page'){
$('#title').attr('disabled','disabled');
}
});
No need to make a seperate js file. Adding this to your function.php will do the same that Matthew showed.
function admin_footer_hook(){
?>
<script type="text/javascript">
if(jQuery('#post_type').val() === 'post'){
jQuery('#title').prop('disabled', true);
}
</script>
<?php
}
add_action( 'admin_footer-post.php', 'admin_footer_hook' );
This Solution Will disable clicking on the post title and editing it using CSS. CSS targets post type "page" only. It has been tested on Gutenberg visual editor. Users Can still edit title from "Quick Edit".
Add this code to your functions.php file.
function disable_title_edit() {
if(!current_user_can('administrator')){
if( !current_user_can('administrator')){ ////Only allow Admin
echo '<style>.post-type-page .edit-post-visual-editor__post-title-wrapper{
pointer-events: none;
}</style>'; } }
}
add_action('admin_head', 'disable_title_edit', 100);

Wordpress: enqueue a script only if a widget is used

There is a way to enqueue a script only if a widget is used (pay attention, not if is active, but if it is present inside a sidebar in a page/post)? Or even better: there is a way to enqueue a script only if a particular string appears inside a sidebar?
Just enqueue the script or stylesheet in the widget function. This is the easiest and best approach.
public function widget( $args, $instance ) {
// outputs the content of the widget
// Enqueue a script needed for
// the Widget's output
wp_enqueue_script( 'your_script', $path, $deps );
// Rest of widget output goes here...
}
I haven't actually tested, this but one possible solution would be to enqueue your script to the footer.
If widget is used
When you build the widget, you can add some code to the widget() function of your widget's class (the function at actually outputs the widget to the screen). You could call wp_enqueue_script() from here, just make sure you flag it to be used in the footer.
This will print your script where wp_footer() is called rather than where wp_head() is called, but only if the widget is invoked on the page.
If a string appears in the sidebar
Basically, just filter the sidebar for your string. If the string is present, enqueue your script to the footer the same way you would with a widget.
(Update) Alternatives
There are two other things you can do. First, you can use jQuery to namespace your functionality. Basically, give your widget a unique ID (say "my-unique-id"), then download your script asynchrounously:
jQuery(document).ready(function() {
if( jQuery('#my-unique-id').length > 0 ) {
jQuery.getScript( [your-script-url] );
}
}
This code will check to see if your widget ID is on the page ... if so, it downloads your script from the server, if not, it does nothing. You can also build this code in PHP to include either a relative or absolute reference to your script file. It's up to you.
Alternatively, you could just include your script in an inline <script> block in your widget's code. This will work the way you want it to, but it breaks all kinds of standard coding practices. Code should typically be in the <header> or placed directly before the closing </body> tag ... but you can really put it anywhere you want.
Yes.
I considered 'wp_footer' hook because this hook is executed at footer,and is probably the best way to add scripts only where the widget is used.
class Your_Widget extends WP_Widget{
function widget( $args, $instance ) {
add_action('wp_footer',array($this,'front_end_scripts'));
}
function front_end_scripts(){
?><script type="text/javascript">
console.log('this works!');
/*
Or if you need external scripts then you may use
$.getScript([your-script-url] );
*/
</script> <?php
}
}

How can I use add_filter for a specific page template?

In Wordpress I have a page template called designers.php.
When loading, it reads the slug to get a uniqe ID, then calls the DB to retrieve designer information.
I want to use this information to alter the page title, using the designer name in the title tag.
I've tried using the add_filter in my designers.php file, but it's not working:
add_filter('wp_title', 'set_page_title');
function set_page_title($title) {
global $brand;
return 'Designer '.$brand['name'].' - '.get_bloginfo('name');
}
I'm, guessing the add_filter must either be located inside a plugin or in functions.php file.
How can I achieve what I'm trying to do?
UPDATE
The function is never fired as long as I use wp_title. If I change it to init (for testing), the function is fired.
So why does the add_filternor work for wp_title?
You are almost right. The filter must reside in function.php, and is called to modify the title. You can add the filter conditionally. Use this function is_page_template() to determine if wordpress is rendering your template
Try to modify your function like this:
add_filter('wp_title', 'set_page_title');
function set_page_title($title) {
global $brand;
if (is_page_template('designer.php'))
return 'Designer '.$brand['name'].' - '.get_bloginfo('name');
else
return $title;
}
First of all add_filter must either be located inside a plugin or in functions.php file.
Then, maybe you have to set the priority for the filter :
add_filter('wp_title', 'set_page_title',1);
function set_page_title() {
global $brand;
return 'Designer '.$brand['name'].' - '.get_bloginfo('name');
}
And check the <title> meta in your header.php theme.
<title><?php wp_title(); ?></title>

Resources