I have researched several similar questions on stackoverflow about this topic that already have answers.
Some of the answers don't seem to fully work and some are just over my head.
I have been reading and reworking my code for over a week so I though I would try asking again with more detail than the other questions had.
I've written a very simple WordPress plugin that's only purpose in life is to load a fully functional editor via ajax.
Here is a screencast of this plugin working (with errors):
http://screencast.com/t/eyrTdbUy
I think that if my question can be answered it will help a lot of people.
Here is exactly what the plugin does.
It loads my custom page template instead of the theme template. In this template there is a editor created with the wp_editor function (to load the required files) and a link to add a new editor.
When you click the "add editor" link a new editor is created using the wp_editor function via ajax then initialized with javascript and new link is added to add another.
This only works if a user is logged in.
I wouldn't advise installing this on your active website because it will take over your pages. This plugin is for example only so it should only be installed on tester sites.
Here's the problems...
The first instance of the ajax loaded editor works but there is the following errors when you click the tabs to switch back and forth from visual to text
"TypeError: e is undefined"
"TypeError: c is undefined"
The "TypeError: e is undefined" also happens when the first new editor is loaded.
After the first instance is loaded another editor cannot be added.
So my question is... What is wrong with my code?
The plugin is made up of 4 files.
File 1 is the plugin file "load_editor.php" (it just includes the functions):
include('functions.php');
File 2 is the functions file "functions.php":
<?
// load custom editor template
function load_editor_template( $template )
{
$template = plugin_dir_path( __FILE__ ) . 'template.php';
return $template;
}
add_filter( 'template_include', 'load_editor_template' );
// load javascript
function load_editor_scripts() {
wp_enqueue_script( 'load_editor', plugins_url() . '/load_editor/js/load_editor.js', array(), '', true );
wp_enqueue_script( 'jquery');
}
add_action( 'wp_enqueue_scripts', 'load_editor_scripts' );
// create new editor
function load_editor_new_editor() {
$id = $_POST['id'];
$number = $_POST['number'];
$next = $number + 1;
$full_id = $id.$number;
echo "<h1>Editor $number</h1>";
$content = '<p>This is example content.</p>';
wp_editor($content, $full_id, array('textarea_rows' => 3));
// initiate new editor
echo "<script>
tinyMCE.execCommand('mceAddEditor', true, $full_id);
tinyMCE.init(tinyMCEPreInit.mceInit[$full_id]);
</script>";
// create "add new" text
echo "<div><a onclick=\"load_new_editor('editor', $next);\" href='javascript:void(0);'>Click here</a> to add another editor</div>";
die();
}
add_action( 'wp_ajax_load_editor_new_editor', 'load_editor_new_editor' );
File 3 is the template file "template.php" :
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Load Editor</title>
<?php wp_head(); ?>
</head>
<body>
<? wp_editor('Ecample content', 'id', array('textarea_rows' => 3)); ?>
<div id="add"><a onClick="load_new_editor('editor', 1);" href="javascript:void(0);">Click here</a> to add an editor</div>
<div id="editor_container">
<!-- Editors will load here -->
</div>
<script>
<?
echo 'ajaxurl = "'.admin_url('admin-ajax.php').'";';
?>
</script>
<?php wp_footer(); ?>
</body>
</html>
And file 4 is the javascript file "load_editor.js":
function load_new_editor(id, number){
// remove click to add
jQuery('#add').remove();
var fullId = id + number;
var data = {
'action': 'load_editor_new_editor',
'number': number,
'id': id
};
jQuery.post(ajaxurl, data, function(response) {
//add new editor
jQuery('#editor_container').append(response);
});
}
I've also put it on github here:
enter link description here
Thank you so much for any help that you can give. I've been trying to get this to work for so long it's frying my brain. I even hired a programmer via elance and he was unable to get as far as I did.
This is the best I can come up with and I think it is good enough for me.
Everything is working except the quicktags and I can live without them.
I removed the javascript from funtions.php
<?
// load custom editor template
function load_editor_template( $template )
{
$template = plugin_dir_path( __FILE__ ) . 'template.php';
return $template;
}
add_filter( 'template_include', 'load_editor_template' );
// load javascript
function load_editor_scripts() {
wp_enqueue_script( 'load_editor', plugins_url() . '/load_editor/js/load_editor.js', array(), '', true );
wp_enqueue_script( 'jquery');
}
add_action( 'wp_enqueue_scripts', 'load_editor_scripts' );
// create new editor
function load_editor_new_editor() {
$id = $_POST['id'];
$number = $_POST['number'];
$next = $number + 1;
$full_id = $id.$number;
echo "<h1>Editor $number</h1>";
$content = '<p>This is example content.</p>';
wp_editor($content, $full_id, array('textarea_rows' => 3));
// create "add new" text
echo "<div id='add'><a onclick=\"load_new_editor('editor', $next);\" href='javascript:void(0);'>Click here</a> to add another editor</div>";
die();
}
add_action( 'wp_ajax_load_editor_new_editor', 'load_editor_new_editor' );
Then I changed the following on load_editor.js
Added the quicktags function to get the tabs to work without error
Called tinymce.init with the settings that WordPress uses
I think that's it.
// JavaScript Document
function load_new_editor(id, number){
// remove click to add
jQuery('#add').remove();
var fullId = id + number;
var data = {
'action': 'load_editor_new_editor',
'number': number,
'id': id
};
jQuery.post(ajaxurl, data, function(response) {
//add new editor
jQuery('#editor_container').append(response);
// this is need for the tabs to work
quicktags({id : fullId});
// use wordpress settings
tinymce.init({
selector: fullId,
theme:"modern",
skin:"lightgray",
language:"en",
formats:{
alignleft: [
{selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: {textAlign:'left'}},
{selector: 'img,table,dl.wp-caption', classes: 'alignleft'}
],
aligncenter: [
{selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: {textAlign:'center'}},
{selector: 'img,table,dl.wp-caption', classes: 'aligncenter'}
],
alignright: [
{selector: 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles: {textAlign:'right'}},
{selector: 'img,table,dl.wp-caption', classes: 'alignright'}
],
strikethrough: {inline: 'del'}
},
relative_urls:false,
remove_script_host:false,
convert_urls:false,
browser_spellcheck:true,
fix_list_elements:true,
entities:"38,amp,60,lt,62,gt",
entity_encoding:"raw",
keep_styles:false,
paste_webkit_styles:"font-weight font-style color",
preview_styles:"font-family font-size font-weight font-style text-decoration text-transform",
wpeditimage_disable_captions:false,
wpeditimage_html5_captions:true,
plugins:"charmap,hr,media,paste,tabfocus,textcolor,fullscreen,wordpress,wpeditimage,wpgallery,wplink,wpdialogs,wpview",
selector:"#" + fullId,
resize:"vertical",
menubar:false,
wpautop:true,
indent:false,
toolbar1:"bold,italic,strikethrough,bullist,numlist,blockquote,hr,alignleft,aligncenter,alignright,link,unlink,wp_more,spellchecker,fullscreen,wp_adv",toolbar2:"formatselect,underline,alignjustify,forecolor,pastetext,removeformat,charmap,outdent,indent,undo,redo,wp_help",
toolbar3:"",
toolbar4:"",
tabfocus_elements:":prev,:next",
body_class:"id post-type-post post-status-publish post-format-standard",
});
// this is needed for the editor to initiate
tinyMCE.execCommand('mceAddEditor', false, fullId);
});
}
Here is a screencast of it working.
http://screencast.com/t/Psd9IVVY
If anyone knows how to get the quicktags to show, I would love to know.
Also, if you spot something wrong with my code let me know.
I have updated the github if you want to download it here:
https://github.com/ccbgs/load_editor
( Answer found here: https://wordpress.stackexchange.com/questions/51776/how-to-load-wp-editor-through-ajax-jquery/192132 )
1) in functions.php,add:
add_action('init','my_wpEditOUPUTT'); function my_wpEditOUPUTT(){
if (isset($_POST['Give_me_editorrr'])){
wp_editor( '' , 'txtrID_'.$_POST['myNumber'], $settings = array( 'editor_class'=>'my_class', 'textarea_name'=>'named_'. $_POST['myNumber'], 'tinymce'=>true , 'media_buttons' => true , 'teeny' => false,));
exit;
}
}
2) inside dashboard HTML page:
<div id="MyPlace"></div> Click to load
<script type="text/javascript">
startNumber = 1;
function myLoad(){ alert('wait 1 sec');
startNumber ++;
jQuery.post('./index.php', '&Give_me_editorrr=1&myNumber='+startNumber ,
function(data,status){
if (status == "success") {
document.getElementById('MyPlace').innerHTML += data; alert("Inserted!");
tinymce.init({ selector: 'txtrID_'+startNumber, theme:'modern', skin:'lightgray'}); tinyMCE.execCommand('mceAddEditor', false, 'txtrID_'+startNumber);
}
});
}
</script>
Related
I am creating a custom wordpress theme and what i want is that; there is a download link, what i want is that users can download only 5 times when the user clicks that link only for 5 times, if the user tries to click the link for the 6th time it automatically hides. I dont have any idea how to do this, also didn't find any relevant solution on google.
here below is my testing code:
<script type="text/javascript">
function myFunction() {
$(document).ready(function(){
$(".gotocls").click(function(){
alert("Hello! I am an alert box!!");
});
});
}
</script>
<a class="dkpdf-button gotocls" onclick="myFunction()" href="downlaod/image.com" target="_blank"><span class="dkpdf-button-icon"><i class="fa fa-file-pdf-o"></i></span> <?php echo $pdfbutton_text;?></a>
i think this might be done with ajax, but i dont have much knowledge of ajax
you don't need onClick in this code I add document.getElementsByClassName('gotocls')[0].style.display = 'none'; when i equals 5 .
$(document).ready(function(){
var i = 0
$(".gotocls").click(function(){
i++
if(i == 5)
document.getElementsByClassName('gotocls')[0].style.display = 'none';
alert("Hello! I am an alert box!!" + i);
});
});
</script>
<a class="dkpdf-button gotocls" id="myLink" href="downlaod/image.com" target="_blank"><span class="dkpdf-button-icon"><i class="fa fa-file-pdf-o"></i></span> <?php echo $pdfbutton_text;?></a>
If you only want to hide the download link in the current session, then simple javascript should do your job.
<script type="text/javascript">
var counter = 0;
function myFunction() {
if(counter === 5){
document.getElementsByClassName('gotocls')[0].style.display = 'none';
}
counter = counter +1;
}
</script>
However when the user refreshes the site, then the download link will be visible again. If you want to store information permanently then you have to use a database.
I wrote the code needed real quick with no tests but it should give you a starting point at least, in your PHP:
/**
* Enqueue a JS file using WP proper action and functions
* 'my-custom-script' can be any name of your fantasy, prepend it with your vendor name and you are good to go
* 'url_to_js_file' MUST be a full URL to your .JS file containing the ajax you need
*/
function our_custom_scripts() {
wp_register_script( 'my-custom-script', 'url_to_js_file.js', array( 'jquery' ), false, true );
wp_localize_script( 'my-custom-script', 'myJsVarName', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ), // Used to make ajax call in WP
) );
wp_enqueue_script( 'my-custom-script' );
}
// Load script
add_action( 'wp_enqueue_scripts', 'our_custom_scripts' );
/**
* What the ajax call will actually trigger thanks to WP AJAX handle
*/
function my_ajax_action() {
/** #var wpdb $wpdb */
global $wpdb;
$clickedLink = $_POST["clicked_link"];
$userId = get_current_user_id();
/*
* Query for the pressed link, that's up to you on how to store data in the database, im going with an easy one
* saving the full link (i would really NOT recommend this :D, its just to show)
*/
$sql = "SELECT * FROM {$wpdb->prefix}my_table_name WHERE link = %s";
$res = $wpdb->get_row( $wpdb->prepare( $sql, array( $clickedLink ) ) );
if ( $canClick = $res["num_pressed"] < 5 ) {
$wpdb->update(
$wpdb->prefix . "my_table_name",
array(
'num_pressed' => ( $res["num_pressed"] + 1 ),
'string_col' => 'val2', //example string col
'int_col' => 3, //example int col
),
array( "user_id" => $userId ), // Where condition
array( "%d", "%s", "%d" ), // updated values format. %s are for strings, %d for integers
array( "%d" ) );// Where condition format
wp_send_json_success();
} else {
wp_send_json_error();
}
}
add_action( 'wp_ajax_my_ajax_action', array( $this, 'my_ajax_action' ) );
add_action( 'wp_ajax_nopriv_my_ajax_action', array( $this, 'my_ajax_action' ) );
Then in your .js file add this:
$(document).ready(function () {
$(".gotocls").click(function (evt) {
var $pressedLink = $(this);
evt.preventDefault(); // Stop doing w/e the browser was trying to do
$.ajax({
url: myJsVarName.ajaxurl,
type: 'POST',
data: {
action: 'my_ajax_action',
clicked_link: $pressedLink.attr("href")
},
timeout: 5000
dataType: 'json',
success: function (response) {
console.log('Your response content', response);
if (response.success) {
window.location.href = $pressedLink.attr("href"); // Proceed with click
}
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
});
})(jQuery);
This should cover the PHP and the JS side of your stuff. The rest is up to you, stackoverflow is not a coding factory, it's a community for advices :D
I'm trying to do a dynamic product gallery based on colours in woocommerce product page. When I click on one colour, example on red, i should see Red Gallery's photos.
To do this i replaced all woocommerce gallery block with a new one created by ajax ( who have same classes of old gallery).
The loading of new photos work fine and I get gallery photos based on colour.
But when ajax load new gallery the slider don't work, I think because the woocommere js, who create the slider, is read only on page load.
I think I should reload some Woocommerce JS Function to recreate slider with his functions, but I don't know how.
This is the php file, which one I create a new gallery, called from ajax:
global $product;
$current_id = "";
if(isset($_POST['prodid']) && $_POST['prodid'] != "" ) {
$current_id = $_POST['prodid'];
$product = new WC_Product($current_id);
}
$columns = apply_filters( 'woocommerce_product_thumbnails_columns', 4 );
$post_thumbnail_id = $product->get_image_id();
$wrapper_classes = apply_filters( 'woocommerce_single_product_image_gallery_classes', array(
'woocommerce-product-gallery',
'woocommerce-product-gallery--' . ( $product->get_image_id() ? 'with-images' : 'without-images' ),
'woocommerce-product-gallery--columns-' . absint( $columns ),
'images',
) );
?>
<figure class="woocommerce-product-gallery__wrapper">
<?php
if ( $product->get_image_id() ) {
$html = wc_get_gallery_image_html( $post_thumbnail_id, true );
} else {
$html = '<div class="woocommerce-product-gallery__image--placeholder">';
$html .= sprintf( '<img src="%s" alt="%s" class="wp-post-image" />', esc_url( wc_placeholder_img_src( 'woocommerce_single' ) ), esc_html__( 'Awaiting product image', 'woocommerce' ) );
$html .= '</div>';
}
echo apply_filters( 'woocommerce_single_product_image_thumbnail_html', $html, $post_thumbnail_id ); // phpcs:disable WordPress.XSS.EscapeOutput.OutputNotEscaped
do_action( 'woocommerce_product_thumbnails' );
?>
</figure>
This is the ajax function called on box colour click
function changeGallery(selected_gallery, productID) {
jQuery(function($) {
var select_color = selected_gallery;
var xhttp;
$.ajax({
url : 'https://mysite.it/wp-admin/admin-ajax.php', // AJAX handler
data : { action : 'load_gallery', gallery : select_color, prodid : productID },
type : 'POST',
beforeSend: function() {
},
success : function( result ){
if( result ) {
$('.woocommerce-product-gallery').html(result);
//Reload here some woocommerce JS functions?
}
}
});
});
}
The way to solve issues like this is to look at the WooCommerce source code to see how the plugin initialises the gallery to begin with. Based on this, I think you need to do something like:
jQuery( '.woocommerce-product-gallery' ).each( function() {
jQuery( this ).wc_product_gallery();
} );
See Github: single-product.js for reference.
I had same problem. The dafoxuk answer is correct, you need to reinitialize ProductGallery class on the .woocomorce-product-gallery. The problem was that this element already has a flexslider entity attached to it. To solve this, just remove that element (.woocomorce-product-gallery) and create a new identical one. (Flexslider doesn't have a way to detach itself from the element as far as I know)
I'm trying to wrap my head around how this actually works in wordpress on the admin back end for a widget I'm trying to create (similar to the custom HTML widget). I've read a few tutorials but the information seems to change and I feel I have just confused myself.
Everything works fine while initializing codemirror and it is applied to the textarea but the errors I'm having are:
When new html is entered into codemirror the save button for the widget doesn't activate.
If I change another field to activate the save button the data from codemirror is not sent or saved.
(function ($) {
$(document).ready( function(){
var editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
editorSettings.codemirror = _.extend(
{},
editorSettings.codemirror,
{
lineNumbers: true,
mode: "text/html",
indentUnit: 2,
tabSize: 2,
autoRefresh:true,
}
);
var editor = wp.codeEditor.initialize( $('#<?php echo $textarea_id; ?>'), editorSettings );
});
})(jQuery);
</script>
I've also tried adding:
$(document).on('keyup', '.CodeMirror-code', function(){
editor.codemirror.save();
$('#<?php echo $textarea_id; ?>').html(editor.codemirror.getValue());
});
but editor.codemirror.getValue() return empty when I display through console.log
Code for Textarea
<p>
<label for="<?php echo $textarea_id; ?>"><?php _e( 'Locked Content:' ); ?></label>
<textarea id="<?php echo $textarea_id; ?>" name="<?php echo $this->get_field_name( 'locked-content' ); ?>" class="widefat"><?php echo esc_textarea( $instance['locked-content'] ); ?></textarea>
</p>
Any help (links to a proper tutorial, advice etc) would be much appreciated JS isn't my strongest language.
I believe this came down to me being an idiot lol I was calling this same block of code from another widget as I was trying to make both widgets textareas into codemirrors.
I changed the name of 2 variables to be more specific towards the widget eg:
var editorSettings
var editor
where changed to:
var cm_editorSettings
var cm_editor
This allowed me to us cm.editor.codemirror.getValue() and return the actual value. Still not sure if this is the correct way to implement it so please correct me if I am wrong but currently the working code to update the textarea and enable save button is as follows
<script type="text/javascript">
(function ($) {
$(document).ready( function(){
var cm_editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
cm_editorSettings.codemirror = _.extend(
{},
cm_editorSettings.codemirror,
{
lineNumbers: true,
mode: "text/html",
indentUnit: 2,
tabSize: 2,
autoRefresh:true,
}
);
var cm_editor = wp.codeEditor.initialize($('#<?php echo $textarea_id; ?>') , cm_editorSettings );
$(document).on('keyup', '.CodeMirror-code', function(){
$('#<?php echo $textarea_id; ?>').html(cm_editor.codemirror.getValue());
$('#<?php echo $textarea_id; ?>').trigger('change');
});
});
})(jQuery);
I'm wondering if there is a way to put my Wordpress attachment link inside of a javascript function. In simple terms, it would function like so:
$attach_url = "<?php echo wp_get_attachment_url(); ?>";
function () {
return $attach_url;
}
More specifically, I'm looking for a way to implement it with Photoswipe's share buttons (full source code here):
$attach_url = = "<?php echo wp_get_attachment_url(); ?>";
(this, function () {
'use strict';
var PhotoSwipeUI_Default =
function(pswp, framework) {
shareButtons: [
{url:'https://www.facebook.com/sharer/sharer.php?u={{attachment_pg_url}}'},
],
getAttachmentPageURL: function ( shareButtonData ) {
return $attach_url;},
parseShareButtonOut: function(shareButtonData, shareButtonOut) {
return shareButtonOut;
},
_updateShareURLs = function() {
var shareButtonOut = '',
shareButtonData,
shareURL,
attachment_pg_url;
for(var i = 0; i < _options.shareButtons.length; i++) {
shareButtonData = _options.shareButtons[i];
attachment_pg_url = _options.getAttachmentPageURL(shareButtonData);
shareURL = shareButtonData.url.replace('{{attachment_pg_url}}', attachment_pg_url );
Any help is much appreciated!
EDIT
Here's my updated code, which is almost working. The js file is interpreting the enqueue script from functions.php. However, the url displayed is <?php echo get_attachment_link(); ?>, rather than the actual link (ex: home.com/attachment-page), which does display correctly when I use this php code in the loop.
How can I get the url to output a link, not the actual php code?
In functions.php:
// Custom Photoswipe Share URL
wp_enqueue_script( 'photoswipe_custom_share_link', get_template_directory_uri() . '/custom_path_here/photoswipe-ui-single-item.js' );
$attach_url = "<?php echo get_attachment_link(); ?>";
wp_localize_script( 'photoswipe_custom_share_link', 'pswp_custom_share', $attach_url );
In the Photoswipe js file (with some extra fixes from my original post):
(this, function () {
'use strict';
var PhotoSwipeUI_Default =
function(pswp, framework) {
shareButtons: [
{url:'https://www.facebook.com/sharer/sharer.php?u={{attach_url}}'},
],
getAttachmentURLForShare: function ( /*shareButtonData */) {
return pswp_custom_share;
},
parseShareButtonOut: function(shareButtonData, shareButtonOut) {
return shareButtonOut;
},
_updateShareURLs = function() {
var shareButtonOut = '',
shareButtonData,
shareURL,
attachment_url;
for(var i = 0; i < _options.shareButtons.length; i++) {
shareButtonData = _options.shareButtons[i];
attachment_url = _options.getAttachmentURLForShare(shareButtonData);
shareURL = shareButtonData.url.replace('{{attach_url}}', encodeURIComponent(attachment_url) );
EDIT
I made the mistake of using quotes in my enqueue script. With the below code, formatting is now correct. The only problem is the url output is "home.com" instead of "home.com/attachment-page."
How can I define the dynamically generated attachment page url outside of the loop? Do I need to echo it?
$attach_url = get_attachment_link($attachment->ID);
EDIT - SOLVED!
I needed to use JavaScript enqueue to get base url of attachment in the loop. (Based on the answer here and with thedarkcoder's help).
In functions.php:
// Custom Photoswipe Share URL
function pswp_custom_share()
{
/* Get the ID of the current post */
global $post;
$ID = $post->ID;
/* register the script */
wp_register_script( 'photoswipe_custom_share_link', get_template_directory_uri() . 'custom_path_here/photoswipe-ui-single-item.js', array('jquery'), false, true );
$attach_url = array(
'attachment_page' => get_attachment_link( $ID )
);
wp_enqueue_script( 'photoswipe_custom_share_link' );
wp_localize_script('photoswipe_custom_share_link', 'attach_url', $attach_url);
}
/* If we're not in the admin section call our function on the wp_enqueue_scripts hook */
if ( !is_admin() ) add_action( "wp_enqueue_scripts", "pswp_custom_share", 10 );
In the Photoswipe js file:
getAttachmentURLForShare: function ( /*shareButtonData */) {
return attach_url.attachment_page;
},
You can use WordPress enqueue script function to achieve this
Please follow below link for detailed info
https://code.tutsplus.com/tutorials/how-to-pass-php-data-and-strings-to-javascript-in-wordpress--wp-34699
Let me know if it resolves your problem
It should be possible in theory as PHP is processed server-side before the javascript runs on client side.
I've noticed your script is missing the attachment ID from the wp_get_attachment_url function.
From the Wordpress API Documentation:
<?php echo wp_get_attachment_url( 12 ); ?>
The first step would be to test the functionality on a basic level by echoing the attachment URL to the page. Once you've done this, you know that you're hooking into the function correctly.
Then assign that value to a JavaScript variable and try running some sort of alert or console log to validate that you can successfully parse the URL to a global JS variable.
Then see if you can access that variable from inside a function. If you can step through each of the above basic steps then it should be more than possible for you to parse this data into the Photoswipe plugin.
Let me know if you get stuck, I will attempt to help in any way I can.
Recently I found the following javascript from another thread on this forum;
var $content=$('div.leg_ol');
var $links=$('.leg_test').hover(function(){
var index= $links.index(this);
$content.stop(true,true).hide().eq(index).fadeIn();
},function(){
$content.stop(true,true).hide().eq(index);
});
(I would link to the OP, but unfortunately have lost the page).
JSFIDDLE: https://jsfiddle.net/mfyctwvs/1/
The code does exactly what I want to do - in theory, now I am pretty much completely new to js, so this is a very tricky area for me - please bear with me on this.
When I post the code in functions.php it causes my whole site to stop working, I assume because it cannot read it or there is some conflict?
So my first thought, looking at jsfiddle was the js version and that it is specified as no wrap in . If I change either of these the code does not work.. ..so 1. Am I making a newb mistake trying to include incompatible js in my functions.php (probably yes?) & 2. is there a straightforward change I can make to get this working in my functions.php?
I have been searching on this for hours & am sure that I could get this working with some adjustments?
FYI; Functions.php
<?php// Set path to WooFramework and theme specific functions
$functions_path = get_template_directory() . '/functions/';
$includes_path = get_template_directory() . '/includes/';
// Don't load alt stylesheet from WooFramework
if ( ! function_exists( 'woo_output_alt_stylesheet' ) ) {
function woo_output_alt_stylesheet () {}
}
// WooFramework
require_once ( $functions_path . 'admin-init.php' ); // Framework Init
if ( get_option( 'woo_woo_tumblog_switch' ) == 'true' ) {
//Enable Tumblog Functionality and theme is upgraded
update_option( 'woo_needs_tumblog_upgrade', 'false' );
update_option( 'tumblog_woo_tumblog_upgraded', 'true' );
update_option( 'tumblog_woo_tumblog_upgraded_posts_done', 'true' );
require_once ( $functions_path . 'admin-tumblog-quickpress.php' ); // Tumblog Dashboard Functionality
}
/*-----------------------------------------------------------------------------------*/
$includes = array(
'includes/theme-options.php', // Options panel settings and custom settings
'includes/theme-functions.php', // Custom theme functions
'includes/theme-actions.php', // Theme actions & user defined hooks
'includes/theme-comments.php', // Custom comments/pingback loop
'includes/theme-js.php', // Load JavaScript via wp_enqueue_script
'includes/theme-plugin-integrations.php', // Plugin integrations
'includes/sidebar-init.php', // Initialize widgetized areas
'includes/theme-widgets.php', // Theme widgets
'includes/theme-advanced.php', // Advanced Theme Functions
'includes/theme-shortcodes.php', // Custom theme shortcodes
'includes/woo-layout/woo-layout.php', // Layout Manager
'includes/woo-meta/woo-meta.php', // Meta Manager
'includes/woo-hooks/woo-hooks.php' // Hook Manager
);
// Allow child themes/plugins to add widgets to be loaded.
$includes = apply_filters( 'woo_includes', $includes );
foreach ( $includes as $i ) {
locate_template( $i, true );
}
// Load WooCommerce functions, if applicable.
if ( is_woocommerce_activated() ) {
locate_template( 'includes/theme-woocommerce.php', true );
}
/*-----------------------------------------------------------------------------------*/
/* You can add custom functions below */
/*-----------------------------------------------------------------------------------*/
add_action( 'init', 'woo_custom_move_navigation', 10 );
function woo_custom_move_navigation () {
// Remove main nav from the woo_header_after hook
remove_action( 'woo_header_after','woo_nav', 10 );
// Add main nav to the woo_header_inside hook
add_action( 'woo_header_inside','woo_nav', 10 );
} // End woo_custom_move_navigation()
/* Testing stuff for mobile */
function woo_load_responsive_meta_tags () {
$html = '';
$html .= "\n" . '<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame -->' . "\n";
$html .= '<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />' . "\n";
echo $html;
} // End woo_load_responsive_meta_tags()
add_action('wp_enqueue_scripts', function () {
wp_enqueue_script(
'user-scripts',
get_template_directory_uri() . '/functions/user-scripts.js',
array('jquery') // any script dependancies. i.e. jquery
);
});
?>
In wordpress you in ject your javascript files into your theme using the wordpress api/hooks. the method you want is wp_enqueue_script. Here are the docs
It's used like this:
add_action('wp_enqueue_scripts', 'addScript');
function addScript() {
wp_enqueue_script(
'script-name',
get_template_directory_uri() . '/path-to-your-script.js',
array('jquery') // any script dependancies. i.e. jquery
);
}
Depending on the version of php you have, you can inline the function:
add_action('wp_enqueue_scripts', function () {
wp_enqueue_script(
'script-name',
get_template_directory_uri() . '/path-to-your-script.js',
array('jquery') // any script dependancies. i.e. jquery
);
});
From the script provided by #atmd the following code worked.
add_action('wp_enqueue_scripts', function () {
wp_enqueue_script(
'script-name',
get_template_directory_uri() . '/path-to-your-script.js',
array('jquery') // any script dependancies. i.e. jquery
);
});
A precondition required was that the script was located in the /functions/ folder of the theme used. The original code posted works perfectly on the site.