How to use "get_template_directory_uri" in javascript function - javascript

This is a part of my WordPress PHP file code, in this I wrote a JavaScript code and I would like to display the names, images from the query.
Names are displayed but images are not displaying, then I added get_template_directory_uri(), after adding get_template_directory_uri() it is showing error in console like this "Uncaught Syntax Error: missing ) after argument list".
All images are stored in WordPress theme image folder.
How to write javascript code to display images?
Please Help me out from this problem.
Thanks.
function partyFunction(){
debugger;
$postdata = {};
$postdata["partyId"]=$("#partydropdown").val();
$.post('<?php echo get_template_directory_uri() ?
>/GetPartiesData.php',$postdata,function (data) {
debugger;
console.log(data);
var stringreplace = data.replace(/['"]+/g, '');
console.log(stringreplace);
var res = stringreplace.split(",");
console.log(res);
$("#partyBody").empty();
$("#partyBody").html('');
$("#partyBody").append("<tr>"+
"<td>"+res[1]+"</td>"+
"<td><img src='"+<?php echo get_template_directory_uri() ?
>/img/++res[2]+"' style='padding:5px;vertical-align: middle;border-style:
none;width:129px;height:109px;' ></td>"+
"<td><img src='"+res[3]+"' style='padding:5px;vertical-align:
middle;border-style: none;width:129px;height:109px;' ></td>"+
"<td><a href='"+res[4]+"' target='_blank'>click here</a></td>"+
"</tr>");
});
}

//Add code in function.php
function theme_directory_uri(){
wp_localize_script( 'ajax-login-script', 'uri_object', array(
'theme_directory_uri' => get_template_directory_uri()
));
}
add_action('init', 'theme_directory_uri');
//get in javascript
var theme_uri = uri_object.theme_directory_uri;

Method 1:
Assign it to a global variable in your php file then call it in javascript
like this at top of your .php file
<script>
template_directory = "<?php echo get_template_directory_uri() ?>"
</script>
then use template_directory like this
$.post(template_directory+'/GetPartiesData.php',$postdata,function (data) {
same like this use in image src also.
Method 2:
Use wordpress enqueue functions
wp_register_script( 'template-directory', 'myscript_url' );
wp_enqueue_script( 'template-directory' );
wp_localize_script( 'template-directory', 'directory_name', array( 'templateUrl' => get_stylesheet_directory_uri() ) );
and use this in your script use like this
template_directory = directory_name.templateUrl;
$.post(template_directory+'/GetPartiesData.php',$postdata,function (data) {

Uncaught SyntaxError: missing )
<img src='"+<?php echo get_template_directory_uri() ?>/img/++res[2]+"'
Replace with:
<img src='<?=get_template_directory_uri()?>/img/"+res[2]+"'
You missed semicolon the end of statement:
<?php echo get_template_directory_uri(); ?>
- ^ just missed
P.S. you have used same line more than once, kindly ensure all lines have been modified.

Related

Wordpress PHP link inside Javascript (for Photoswipe Custom Share URL)

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.

Rendering a Wordpress shortcode with Javascript from a JSON object?

I'm currently working on a Wordpress site. I'm building a custom plugin that allows for lazy loading of custom post types.
Some of these post types contain shortcodes, that I need to display. I have a primary Javascript file that makes Ajax requests to my PHP code in my plugin, which returns a JSON object containing the shortcode like this:
Object {shortcode: "[embedyt]https://www.youtube.com/watch?&height=300[/embedyt]"}
I'm then trying to display this shortcode on the front-end, since I'm dynamically building HTML blocks based on the JSON response.
However, when I try to output the shortcode to the page via the Javascript, it just displays as text, like this:
Here's my PHP code and Javascript:
$packet = array();
$formatted_url = "[embedyt]" . $youtube_root . $video_id . "&height=300" . "[/embedyt]";
$packet["shortcode"] = do_shortcode($formatted_url);
echo json_encode($packet); // This sends a response back to the Ajax request
And:
$.ajax({
type: 'POST',
url: tlas_lazy_load.ajax_url,
data: {
action: 'tlas_lazy_load',
post_type: post_type,
posts_per_page: 6,
paged: page
},
success: function(packet) {
response = JSON.parse(packet);
for(var i = 0; i < response.length; i++) {
build_lazy_load("#lazy-load-row", packet[i], i);
}
}
});
function build_lazy_load(element, packet, index) {
var block = "";
block += "<div class=\"col-md-4\">";
block += " <div class=\"video-individual\">";
block += " <div class=\"panel panel-default\">";
block += " <div class=\"panel-body\" id=" + index + ">";
block += packet.shortcode;
block += " <\/div>";
block += " <\/div>";
block += " <\/div>";
block += "<\/div>";
$(element).append(block);
};
What gives me hope that this can be done is the answer to this question:
Wordpress: Outputting shortcode with Javascript?
And I'm following along with what that person suggested. However can this be done?
Update:
So I can display the shortcode if I do this in enqueue scripts method:
add_action( 'wp_enqueue_scripts', 'tlas_lazy_load_enqueue_scripts' );
function tlas_lazy_load_enqueue_scripts() {
wp_enqueue_script( 'tlas-lazy-load', plugins_url( 'js/tlas_lazy_load.js', __FILE__ ), array('jquery'), '1.0', true );
wp_localize_script( 'tlas-lazy-load', 'tlas_lazy_load', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
// BELOW
'videos_shortcode' => do_shortcode("[embedyt]" . $youtube_root . $video_id . "&height=300" . "[/embedyt]")
));
}
By setting it as a localized variable which my Javascript can access. The problem is that I have to add the shortcode after this function has already been declared. I tried localizing it later within the file in my above function by doing:
...
$packet = array();
$formatted_url = "[embedyt]" . $youtube_root . $video_id . "&height=300" . "[/embedyt]";
wp_localize_script( 'tlas-lazy-load', 'tlas_lazy_load', array(
'videos_shortcode' => do_shortcode($formatted_url)
));
...
But this didn't work, it simply returned nothing. I'm on the right track (I think?) but I'm not sure how you can dynamically localize a script/Javascript variable.

Enqueue js in wordpress with charset

I have script
<script src="js/app/script.js" charset="iso-8859-1"></script>
I need to enqueue this js in wordpress with charset. How can I do it ?
I tried do it like that
private static function includeScriptWithCharset($path, $charset){
// I need charset="iso-8859-1"
wp_enqueue_script ($path, plugins_url($path). " ". $charset);
}
I know this question is quite old now, however I have the answer for this, in case this still helps Serg, or helps anyone else who comes across this issue.
The way to do this is to use the WordPress 'script_loader_tag' hook as follows:
// First enqueue your scripts as follows:
wp_enqueue_script( 'my-script-handle', get_stylesheet_directory_uri() . '/some.js', array( 'jquery' ), '6.0');
wp_enqueue_script( 'my-other-handle', get_stylesheet_directory_uri() . '/someother.js', array( 'jquery' ), '6.0');
// Next use the script loader hook as follows:
function my_async_scripts( $tag, $handle, $src ) {
// the handles of the enqueued scripts we want to async
$async_scripts = array( 'my-script-handle', 'my-other-handle' );
if ( in_array( $handle, $async_scripts ) ) {
return '<script type="text/javascript" src="' . $src . '" charset="iso-8859-1"></script>' . "\n";
}
return $tag;
}
add_filter( 'script_loader_tag', 'my_async_scripts', 10, 3 );

How to add javascript to a wordpress site

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.

Load Wordpress Editor Via Ajax Plugin

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>

Categories