Wordpress Custom Theme: mixing php and javaScript? - javascript

I am building a custom wordpress theme and I am trying to add some JavaScript functions.
The main function I want to add is a div that changes color over time. The colors it changes to are defined by the theme color settings in the Customize register. I have added those color settings boxes as show below through my functions.php:
$wp_customize->add_setting('color1', array('default' => '#000000', 'transport'=>'refresh',));
$wp_customize->add_control(new WP_Customize_Color_Control($wp_customize, 'color1_CNTL', array(
'label' => __('Color 1', 'myTheme'),
'section' => 'colors',
'settings' => 'color1',)));
all of that works fine and I can use it in the Customize register on my admin page. Now, the only thing I'm wondering is, how do I use the value of color 1 in my javaScript code? I know that if I wanted to use it in css I would just have to use
<?php echo get_theme_mod('color1'); ?>
but that doesn't work in JavaScript. Any ideas?

The "WordPress way" would be to localize the script.
Utilize wp_localize_script
Overview:
Register a script in your theme (usually in your functions.php
file). See here:
wp_enqueue_script
Localize the script
Then, access that value via your javascript.
Minimal complete example (compiled from WP docs):
PHP:
add_action('wp_enqueue_scripts', 'my_theme_scripts');
function my_theme_scripts() {
// Register the script first.
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Now we can localize the script with our data.
$color_array = array( 'color1' => get_theme_mod('color1'), 'color2' => '#000099' );
wp_localize_script( 'some_handle', 'object_name', $color_array );
// The script can be enqueued now or later.
wp_enqueue_script( 'some_handle' );
}
Javascript (in your 'myscript.js' file);
// Access the color via the object name defined in localize_script
var color = object_name.color1;

prob
var myvariable='<?php echo get_theme_mod("color1");?>'; //note the surrounding ''!
if you are having issues accessing the variable, declare it a global.

Related

Wordpress execute javascript file only if user is not logged in

I'm trying to execute a javascript file in wordpress only if the user is not logged in, but I can't see why it's not working. This is the code I'm using:
<?php
if ( is_user_logged_in() ) {
echo 'Ok!';
} else {
wp_enqueue_script(
'ads'
);
}
?>
And this is what I have in functions.php to register the file:
wp_register_script(
'ads',
get_bloginfo('template_directory') . '/js/ads.js'
);
Any ideas? Thanks in advance!
wp_enqueue_script() should be run on the wp_enqueue_scripts hook. This should also be encapsulated in a function, or at least a closure/anonymous function.
Side note, you'll want to start properly formatting/indenting code now - future you thanks you!
A. You're checking if a user "is" logged in. You can just make sure that is_user_logged_in() is returning false with the use of the "Not" Logical Operator: !.
B. You don't need to register your script, as wp_enqueue_script will register it for you. You really only need to register scripts if you're getting more fancy like loading scripts only if a shortcode is active on a page.
C. Typically you'll want to prefix your script/style handles, since they should be unique, there can be conflicts otherwise.
D. Typically you'll want to use get_template_directory_uri() or get_stylesheet_directory_uri() over get_bloginfo() since get_bloginfo( $directory_type ) is literally just a wrapper for those functions.
Something like this will get you started:
add_action( 'wp_enqueue_scripts', 'load_ads_script' );
function load_ads_script(){
if( !is_user_logged_in() ){
// The "!" makes sure the user is _not_ logged in.
wp_enqueue_script( 'jacob-k-ads', get_stylesheet_directory_uri().'/js/ads.js' );
}
}

Add options to a Wordpress plugin Custom Post Type via child theme functions.php

I'm using Uncode theme for a site. It has a core custom post type called 'portfolio'.
I need to add an option to this CPT so that it shares the tags with regular posts.
I have found the file in the theme core where the CPT is registered and added the following and it works:
'taxonomies' => array('portfolio_category', 'post_tag')
However, as editing core files is a big no no, I'm wondering if there is a way of doing this through my own functions file so it is future proof?
EDIT: It's apparent that I've misunderstood!
Looks like register_taxonomy_for_object_type is what you're after.
The WP Codex has this to say:
register_taxonomy_for_object_type()
Add a registered Taxonomy to a registered Post Type.
register_taxonomy_for_object_type( 'post_tag', 'portfolio' );
Original answer:
From the WP Codex:
register_post_type()
Create or modify a post type. register_post_type should only be invoked through the 'init' action. It will not work if called before 'init', and aspects of the newly created or modified post type will work incorrectly if called later.
(addtl. emphasis mine)
This being the case, you could create a function
function igloobob_portfolio_cpt_mod() {
register_post_type('portfolio', $args);
}
add_action('init', 'igloobob_portfolio_cpt_mod', 999);
where $args basically duplicate's the Uncode theme's arguments to register_post_type, save for your modification. The 999 priority arg is to ensure that it executes after the parent theme has already registered the post type.

TypeError Jquery(...).function is not a function

I'm having an issue with calling a method that has got me completely stumped. I have a set of methods in an external js class that's used for libraries outside core js for the WP theme.
(Sorry About the unending line)
external.js
(function(a){
var b=0;a.fn.mobileMenu=function(c){function e(a){return a.is("ul, ol")}function f(){return a(window).width()<d.switchWidth}function g(c){if(c.attr("id")){return a("#mobileMenu_"+c.attr("id")).length>0}else{b++;c.attr("id","mm"+b);return a("#mobileMenu_mm"+b).length>0}}function h(a){if(a.val()!==null){document.location.href=a.val()}}function j(b){b.css("display","none");a("#mobileMenu_"+b.attr("id")).show()}function k(b){b.css("display","");a("#mobileMenu_"+b.attr("id")).hide()}function l(b){if(e(b)){var c='<div class="td_mobile_menu_wrap"><select id="mobileMenu_'+b.attr("id")+'" class="mobileMenu">';c+='<option value="">'+d.topOptionText+"</option>";b.find("li").each(function(){var b="";var e=a(this).parents("ul, ol").length;for(i=1;i<e;i++){b+=d.indentString}var f=a(this).find("a:first-child").attr("href");var g=b+a(this).clone().children("ul, ol").remove().end().text();c+='<option value="'+f+'">'+g+"</option>"});c+="</select></div>";b.parent().append(c);a("#mobileMenu_"+b.attr("id")).change(function(){h(a(this))});j(b)}else{alert("mobileMenu will only work with UL or OL elements!")}}function m(a){if(f()&&!g(a)){l(a)}else if(f()&&g(a)){j(a)}else if(!f()&&g(a)){k(a)}}var d={switchWidth:td_switch_width_normal,topOptionText:"Menu",indentString:"-"};return this.each(function(){if(c){a.extend(d,c)}var b=a(this);a(window).resize(function(){m(b)});m(b)})}})(jQuery);
And then the core
site.js
jQuery('#td-top-menu .sf-menu').mobileMenu();
and i end up with the error:
Uncaught TypeError: jQuery(...).mobileMenu is not a function
Somewhere along the line, i've managed to break this code and yet i'm not truly sure. I've stripped my header down to just the necessary scripts and nothing causes the error. My current JQuery CDN is the standard downloaded one from google cdn. I was under the impressional that i would get this issue because it cannot resolve the method. But if both scripts are there (I've logged external.js method to see that the script isn't broken), i don't see why it's throwing this error.
The site is http://whatzbuzzing.com to see the error first hand. As a wordpress distribution, i was under the impression that something has gone wrong outside the two files shown because they haven't been edited at all.
In accordance with the order of requests in Chrome Networks panel, you're loading external.js before jquery.min.js. Maybe you could try to fetch jquery.min.js before fetching of external.js? Sorry if I missed anything in your question.
this happens when multiple jquery files are loaded, not a very uncommon thing in a wordpress site.
in your case the problem is here
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script>
jquery comes bundled with wordpress, all you have to do is to properly enqueue your script with jquery as a dependency
function enqueue_my_external_script() {
wp_enqueue_script( 'externaljs', '//example.com/path/to/external.js', array( 'jquery') );
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_external_script' );
if you're calling this from a theme you can use get_template_directory_uri to get the theme directory's url like this
function enqueue_my_external_script() {
wp_enqueue_script( 'externaljs', get_template_directory_uri() . '/path/to/external.js', array( 'jquery') );
}
add_action( 'wp_enqueue_scripts', 'enqueue_my_external_script' );
wp_enqueue_script function
wp_enqueue_scripts action hook

Adding a variable into a page - wordpress

When I create pages within Wordpress, the call to action links on those pages always have the same URL. I want to be able to globalize this variable but am struggling to find a good way to do it.
If I were making simple PHP pages I could simply include e.g.
$URLpath = "http://example.com/my/page";
Then call this in the html:
Call to action
Obviously I can't do this within the Wordpress CMS as it renders as <?=$URLpath?>
I could add, say, Call to action and replace after the page loads using javascript replace over the whole block of html, but it doesn't feel efficient to do this.
Is there a better way? I'm pretty new to Wordpress.
You can add a shortcode in your functions.php file that prints your cta, or better create a plugin with some parameter that manages this link.
For example in functions.php you could add
function cta_func( $atts ){
$URLpath = "http://example.com/my/page";
return 'Call to action';
}
add_shortcode( 'cta', 'cta_func' );
inside your pages/post you can write simply this shortcode.
...
[cta]
...
Further infos about shortcodes are in the reference of codex
https://codex.wordpress.org/Shortcode_API
A good way to do this within WordPress is to use their wp_localize_script()
In your functions.php file you could use as:
// For sake of example I will put your data inside an array,
// but you can set a single value.
$dataForJS = array(
$URLPath => "http://example.com/my/page"
);
// wp_localize_script() takes 3 parameters:
// 1. Name of the registered script, this is the name you used in wp_register_script()
// here I am naming it "main" but it can be anything.
// 2. Name of the variable.
// This name is then available in your JS and will contain your data.
// 3. The data you want to pass, it can be a single value or array
wp_localize_script( 'main', 'd', $dataForJS );
In your JavaScript, you will be able to access this data by just calling the variable d.
What this does is that if the page requests the "main" script, WordPress will add a script tag with your data inside it and makes sure it is placed before your "main" script runs.

wp_localize_script with handle jquery - wordpress script

I'm looking for next solution. I want faster website so I concat all JS to one file and placed in footer. One of my js is jQuery and I use next hook and function:
if (!function_exists("ef_theme_scripts")) {
function ef_theme_scripts() {
wp_deregister_script('jquery');
wp_register_script('jquery', get_template_directory_uri() . '/js/min/script.min.js', null, null, true);
wp_enqueue_script('jquery');
$params = array(
'ajax_url' => admin_url('admin-ajax.php'),
'ajax_nonce' => wp_create_nonce('user_nonce'),
);
wp_localize_script( 'jquery', 'ajax_object', $params );
}
}
add_action('wp_enqueue_scripts', 'ef_theme_scripts');
I called my handle "jquery" because there can be some scripts (e.g. from plugins) which wants use jquery so I need add called this handle "jquery".
Everything works great except localize. When I rename script handle for example to "custom-jquery" then wp_localize_script works without problem.
I use WP 4.0.1. Thanks for help
IMPORTANT! wp_localize_script() MUST be called after the script it's being attached to has been registered using wp_register_script() or wp_enqueue_script().
More info
I asked a similar question and got the working solution here :
wp_localize_script not working with jquery handle
Basically this has to do with the way that WP works with the jQuery handle, you'll need to
deregister jquery
deregister jquery-core
Use the jquery-core handle on your script
at the end register jquery, with a dependency on jquery-core and passing false for the $scr attribute
Code:
wp_register_script( 'jquery', false, array( 'jquery-core' ), false, true );

Categories

Resources