Call TinyMCE in a WordPress plugin - php

Is there a way to add TinyMCE into my own WordPress plugin?
I have a textarea in my back end script and want to make this area into a TinyMCE WYSIWYG editable field. Is there a way to do that?
This code does not work for me:
<?php
wp_tiny_mce(false,array("editor_selector" => "test"));
?>
<textarea class="test" id="test" name="test"></textarea>
It shows the javascript error
f is undefined
Firebug screenshot:
This didn't work either:
<textarea class="theEditor" id="videogalerie-add_description" name="videogalerie-add_description"></textarea>

This is much easier to do in WordPress 3.3 using the wp_editor() function.
I'm working on a plugin that will add a TinyMCE instance to a theme options page. Here's what it looks like:
// Add TinyMCE visual editor
wp_editor( $content, $id );
Where $content is the stored content and $id is the name of the field. Options can also be passed to customize the TinyMCE functionality, check out the WordPress Codex for more details.

Camden already answered this, but in case somebody needs the full code... Be sure to hook in admin_head, hooking into admin_enqueue_scripts will cause it to load before other scripts, such as jQuery, so it will not work.
add_action("admin_head","load_custom_wp_tiny_mce");
function load_custom_wp_tiny_mce() {
if (function_exists('wp_tiny_mce')) {
add_filter('teeny_mce_before_init', create_function('$a', '
$a["theme"] = "advanced";
$a["skin"] = "wp_theme";
$a["height"] = "200";
$a["width"] = "800";
$a["onpageload"] = "";
$a["mode"] = "exact";
$a["elements"] = "intro";
$a["editor_selector"] = "mceEditor";
$a["plugins"] = "safari,inlinepopups,spellchecker";
$a["forced_root_block"] = false;
$a["force_br_newlines"] = true;
$a["force_p_newlines"] = false;
$a["convert_newlines_to_brs"] = true;
return $a;'));
wp_tiny_mce(true);
}
}
Then somewhere in your template insert a regular textarea:
<textarea id="intro"></textarea>

The following example works for me. Just make sure to use the id of the textarea you want to select in the $a["elements"] variable.
Assuming you have a textarea with the id of 'intro':
// attach the tiny mce editor to this textarea
if (function_exists('wp_tiny_mce')) {
add_filter('teeny_mce_before_init', create_function('$a', '
$a["theme"] = "advanced";
$a["skin"] = "wp_theme";
$a["height"] = "200";
$a["width"] = "800";
$a["onpageload"] = "";
$a["mode"] = "exact";
$a["elements"] = "intro";
$a["editor_selector"] = "mceEditor";
$a["plugins"] = "safari,inlinepopups,spellchecker";
$a["forced_root_block"] = false;
$a["force_br_newlines"] = true;
$a["force_p_newlines"] = false;
$a["convert_newlines_to_brs"] = true;
return $a;'));
wp_tiny_mce(true);
}
?>

The tiny mce function wp_tiny_mce is now depricated. For Latest wordpress you want to use wp_editor
$initial_data='What you want to appear in the text box initially';
$settings = array(
'quicktags' => array('buttons' => 'em,strong,link',),
'text_area_name'=>'extra_content',//name you want for the textarea
'quicktags' => true,
'tinymce' => true
);
$id = 'editor-test';//has to be lower case
wp_editor($initial_data,$id,$settings);
for more instructions just go through the documentation in wordpress
http://codex.wordpress.org/Function_Reference/wp_editor

Following guides from here and there (found thanks to this), here's how I've managed to make something work on wordpress 3.0.5 :
<?php
add_action("admin_print_scripts", "js_libs");
function js_libs() {
wp_enqueue_script('tiny_mce');
}
wp_tiny_mce( false , // true makes the editor "teeny"
array(
"editor_selector" => "tinymce_data"
)
);
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('a.toggleVisual').click(function() {
console.log(tinyMCE.execCommand('mceAddControl', false, 'tinymce_data'));
});
$('a.toggleHTML').click(function() {
console.log(tinyMCE.execCommand('mceRemoveControl', false, 'tinymce_data'));
});
});
</script>
<form method="post" action="">
<ul>
<li>
<span id="submit"><input class="button" type="submit"></span>
<p id="toggle" align="right"><a class="button toggleVisual">Visual</a><a class="button toggleHTML">HTML</a></p>
</li>
<li><textarea style="width:100%;" class="tinymce_data" id="tinymce_data" name="tinymce_data"></textarea></li>
</ul>
</form>

I had a similar problem, and class="theEditor" didn't help me either (at first). I was using a custom post type which didn't include the default editor (ie the supports argument didn't include 'editor').
That meant WordPress didn't include the TinyMCE code. Once I added
add_action( 'admin_print_footer_scripts', 'wp_tiny_mce', 25 );
to my functions.php (based on the code in the the_editor function in general-template.php) it worked fine (with class="theEditor").

Tested and working on wordpress 3.3.1
add to functions or plugin file.
<?php
add_filter('admin_head','ShowTinyMCE');
function ShowTinyMCE() {
// conditions here
wp_enqueue_script( 'common' );
wp_enqueue_script( 'jquery-color' );
wp_print_scripts('editor');
if (function_exists('add_thickbox')) add_thickbox();
wp_print_scripts('media-upload');
if (function_exists('wp_tiny_mce')) wp_tiny_mce();
wp_admin_css();
wp_enqueue_script('utils');
do_action("admin_print_styles-post-php");
do_action('admin_print_styles');
}
?>
for Adding new content..
<?php the_editor($id='content');?>
for editing my content
<?php the_editor($mySavedContent); ?>
this will include the entire rage of scripts / css and code needed to produce a tinyMCE textarea within either your plugin or template files..
hope this helps..
M

I had quite a bit of trouble with this. After searching all day and trying dozens of code examples, I couldn't get Wordpress theme options to save MCE values to database. I tried everything, the jQuery answers, the hidden fields, etc etc. None of that would work for me, probably because I was missing a step somewhere.
Finally I found this page: http://wptheming.com/options-framework-theme/
Download from Github & install as directed (easy). Once installed, the last tab in your theme options has an MCE editor. Enter some test paragraphs. Now open the index.php file in the download to see the examples of how to include each thingy in your page. For example, I open footer.php and add a bit of code.
The only edit I needed to make was:
<?php
$ft = of_get_option('example_editor', 'no entry');
$format_ft = wpautop( $ft, false );
echo ($format_ft);
?>
The function wpautop() from Wordpress adds in paragraph tags, since they aren't ever saved in the wp database. I put that code in my footer to display the contents of the MCE.

Related

How to display data in ckeditor from mysql in PHP

I am new in this field, I used ckeditor but I don't know how to display data in ckeditor through mysql..
My code is
$CKeditor = new CKeditor();
$CKeditor->BasePath = 'manage-site/';
$CKeditor->config['filebrowserBrowseUrl'] = 'ckfinder/ckfinder.html';
$CKeditor->config['filebrowserImageBrowseUrl'] = 'browser/browser.php?type=Images';
$CKeditor->config['filebrowserFlashBrowseUrl'] = 'ckfinder/ckfinder.html?type=Flash';
$CKeditor->config['filebrowserUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
$CKeditor->config['filebrowserImageUploadUrl'] = 'uploader/uploader.php?type=Images';
$CKeditor->config['filebrowserFlashUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';
$CKeditor->editor('page_desc','**page_desc**');
For display content I use
<?php echo stripslashes($details[0]["page_desc"]); ?>
I wanted to display on the place of Page_desc(last Line of Code). How to do that?
You can simply download the ckeditor package and do this simple 2 step
Step 1 : Include the ckeditor.js from your file
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
Step 2 : Include the class name as ckeditor to your textarea
Then you can see the ckeditor with simple step
Note : Make sure the ckeditor.js is in the proper path
Hope this helps you

Save the contents of manipulated div to a variable and pass to php file

I have tried to use AJAX, but nothing I come up with seems to work correctly. I am creating a menu editor. I echo part of a file using php and manipulate it using javascript/jquery/ajax (I found the code for that here: http://www.prodevtips.com/2010/03/07/jquery-drag-and-drop-to-sort-tree/). Now I need to get the edited contents of the div (which has an unordered list in it) I am echoing and save it to a variable so I can write it to the file again. I couldn't get that resource's code to work so I'm trying to come up with another solution.
If there is a code I can put into the $("#save").click(function(){ }); part of the javascript file, that would work, but the .post doesn't seem to want to work for me. If there is a way to initiate a php preg_match in an onclick, that would be the easiest.
Any help would be greatly appreciated.
The code to get the file contents.
<button id="save">Save</button>
<div id="printOut"></div>
<?php
$header = file_get_contents('../../../yardworks/content_pages/header.html');
preg_match('/<div id="nav">(.*?)<\/div>/si', $header, $list);
$tree = $list[0];
echo $tree;
?>
The code to process the new div and send to php file.
$("#save").click(function(){
$.post('edit-menu-process.php',
{tree: $('#nav').html()},
function(data){$("#printOut").html(data);}
);
});
Everything is working EXCEPT something about my encoding of the passed data is making it not read as html and just plaintext. How do I turn this back into html?
EDIT: I was able to get this to work correctly. I'll make an attempt to switch this over to DOMDocument.
$path = '../../../yardworks/content_pages/header.html';
$menu = htmlentities(stripslashes(utf8_encode($_POST['tree'])), ENT_QUOTES);
$menu = str_replace("<", "<", $menu);
$menu = str_replace(">", ">", $menu);
$divmenu = '<div id="nav">'.$menu.'</div>';
/* Search for div contents in $menu and save to variable */
preg_match('/<div id="nav">(.*?)<\/div>/si', $divmenu, $newmenu);
$savemenu = $newmenu[0];
/* Get file contents */
$header = file_get_contents($path);
/* Find placeholder div in user content and insert slider contents */
$final = preg_replace('/<div id="nav">(.*?)<\/div>/si', $savemenu, $header);
/* Save content to original file */
file_put_contents($path, $final);
?>
Menu has been saved.
To post the contents of a div with ajax:
$.post('/path/to/php', {
my_html: $('#my_div').html()
}, function(data) {
console.log(data);
});
If that's not what you need, then please post some code with your question. It is very vague.
Also, you mention preg_match and html in the same question. I see where this is going and I don't like it. You can't parse [X]HTML with regex. Use a parser instead. Like this: http://php.net/manual/en/class.domdocument.php

CSS / Javascript Dropdown Navigation Fix Needed for IE

An ex developer of ours when working on one of our first versions of our internal PHP framework integrated the dropdown element of main navigation using javascript and I need to get a fix applied for IE8 which is causing the dropdown to appear offset even though using CSS displays fine in Firefox / Chrome.
The site in question is http://www.benchmemorials.co.uk/
In the event there is sub menu items from the main navigation that use a dropdown, javascript is called to display this I believe (below)...
<script type="text/javascript">
$(document).ready(function() {
var position = $('#link_why-buy-from-us').offset();
$('.dropdown').css(position);
$('#link_why-buy-from-us').mouseover(function() {
$('.dropdown').show();
});
$('.dropdown').mouseover(function() {
$('.dropdown').show();
});
$('.dropdownstyle').mouseover(function() {
$('.dropdown').show();
});
$('#link_why-buy-from-us').mouseleave(function() {
$('.dropdown').hide();
});
$('.dropdown').mouseleave(function() {
$('.dropdown').hide();
});
$('.dropdownstyle').mouseleave(function() {
$('.dropdown').hide();
});
});
</script>
I'm not too hot on javascript but from what I gather, I presume the above is instructing the drop down to appear below the 'Why Buy from Us' top navigation menu item. As I mention, this is working as expected in Firefox/Chrome.
However, the issue appears to be the fact that somewhere along the line, inline CSS is being generated dynamically for the dropdown class - this is dynamically generating
style="top: 61px; left: 964px; display: none;"
Every file on the server has been searched and nowhere is this specified, my only guess is that the javascript above is somehow creating this line of CSS which is therefore preventing me from altering the position of the dropdown in the IE only stylesheet to fix the display in IE8.
The rest of the code for the dropdown menu from the php file is below:-
<div class="dropdown"><div class="dropdownstyle">
<?php
mysql_select_db($database_config, $config);
$query_sub_pages = "SELECT * FROM `pages` WHERE site_id = '".$current_site_id."' AND menu_location = 'sub' ORDER BY `order` ASC";
$sub_pages = mysql_query($query_sub_pages, $config) or die(mysql_error());
$row_sub_pages = mysql_fetch_assoc($sub_pages);
$totalRows_sub_pages = mysql_num_rows($sub_pages);
$current_sub_link = 0;
do {
$current_sub_link = $current_sub_link + 1;
?>
<p<?php if ($current_sub_link != $totalRows_sub_pages) {echo ' style="margin-bottom: 10px;"';}; ?>><a class="sub_link" href="<?php echo $site_base.$row_sub_pages['page_location']; ?>"><?php echo $row_sub_pages['page_display_name']; ?></a></p><?php //if ($current_sub_link != $totalRows_sub_pages) {echo '<br />';}; ?>
<?php } while ($row_sub_pages = mysql_fetch_assoc($sub_pages)); ?>
</div>
</div>
As you can see, there is no inline CSS applied to .dropdown. All CSS from the sylesheets can be viewed if you inspect element in browser.
Please could anyone advise how or if it is possible to prevent this dynamic CSS positioning from being generated or an alternative / easier method of ensuring the dropdown appears consistently across all browsers including IE?
Thanks in advance.
The positioning is done by this code:
var position = $('#link_why-buy-from-us').offset();
$('.dropdown').css(position);
It takes the position of #link_why-buy-from-us relative to the document, and adds it to the .dropdown element.
I don't know if you're familiar with jQuery, but the code above is written using that JavaScript library. For more documentation about .offset(), look here: http://api.jquery.com/offset/

How can I check the source of all image tags in user input using jQuery

I have a form for user input in which users can add images hosted elsewhere using a form. The images are displayed as a small icon which is both a link and which will load an image into a div with stacking order +1 on hover. The image source address is stored in the link tag only.
I am using a <div /> with contenteditable=true for the user input. The icon is appended when the form is used. The code for this part works fine. What I would like to do is check the source of all image tags to make sure that users are not adding their own html to display full size images in their post.
I am using php on the backend to remove all tags except links and images, but would like to use jQuery to check the src of the image tags before posting.
<img src="my_icon" /> //this is what my form will input
<img src="anything_else"> //this is what I want to prevent
Update: I apologize if this is not clear. Essentially, I don't want the user to be able to input any html of their own. If they want to add an image, they have to use my built in form which inserts something like above.
You could loop over the images and then check the src attribute.
$("img").each(function(index) {
if ($(this).attr("src") == ...) {
// do something
}
}
See http://api.jquery.com/each/ and http://api.jquery.com/attr/ for more information.
Say we have the <div id="editor" /> the jQuery script would look something like this:
var srcs = [];
jQuery ('div#editor img').each (function () {
srcs.push (jQuery (this).attr ('src'));
});
srcs will now hold all the src-attributes from the <img />-tags provided in the <div id="editor" /> tag.
Especially for your site following code alerts the links for all images:
$('.postimage').each(function(){
alert($(this).attr('href'));
});
I have an answer. When users input a < or > in a contenteditable="true" div, the browser replaces them with the html notation < and >. The good news is the images would have never displayed when outputting the user comment. The bad news is that the jQuery based solutions given above will not work to remove the ugly coding. I ended up using php to do it with
$post = $_POST['comment'];
$imgcheck = true;
$stringstart = 0;
while($imgcheck == 'true'){
if($stringstart = strpos($post,'<img',$stringstart)){
if ($stringend = strpos($post,'>',$stringstart)){
$strlength = $stringend - $stringstart +4;
$substring = substr($post,$stringstart,$strlength);
if (!preg_match('~src="\/images\/ImageLink.jpg"~',$substring)){
$post = str_replace($substring, "", $post);
}
else{
$stringstart = $stringend;
}
}
else{
$imgcheck = 'false';
}
}
else{
$imgcheck = 'false';
}
}

How to insert this javascript code inside my template.tpl.php to modify the comment form? (function XX_comment_form DRUPAL)

I´ve got a Drupal site and I need to limit comments length.
So, I´ve found this code:
Inside ghead I should add this:
<script language=”javascript”>
function limit(what,chars,counter) {
if (what.value.length > chars) {
what.value=what.value.substr(0,chars);
alert(‘You exceed to ‘ + chars + ‘chars!’);
}
counting = (chars – what.value.length);
c = document.getElementById(counter);
c.innerHTML = counting;
}
</script>
And I should add this stuff where I put the comment body:
<p><label for=”text”><strong>Text</strong></label> ¦ Chars left: <span id=”count1″>500</span></p>
<textarea name=”[1][2][t]” rows=”10″ cols=”50″ onkeyup=”limit(this,500,’count1′);” onkeydown=”limit(this,500,’count1′);” onblur=”limit(this,500,’count1′);” onfocus=”limit(this,500,’count1′);”></textarea>
My problem is that I have no idea on where to put this actually.
I think this goes inside template.tpl.php file.
I´ve found a custom example, but don´t know how to insert the code above:
/**
* Theme the output of the comment_form.
*
* #param $form
* The form that is to be themed.
*/
function mytheme_comment_form($form) {
// Rename some of the form element labels.
$form['name']['#title'] = t('Name');
$form['homepage']['#title'] = t('Website');
$form['comment_filter']['comment']['#title'] = t('Your message');
// Add some help text to the homepage field.
$form['homepage']['#description'] = t('If you have your own website, enter its address here and we will link to it for you. (please include http://).');
$form['homepage']['#description'] .= '<br/>'. t('eg. http://www.kirkdesigns.co.uk');
// Remove the preview button
$form['preview'] = NULL;
return drupal_render($form);
}
Hope anyone can help me out here, because I´m pretty much clueless.
Thanks!
Rosamunda
Put your javascript code to comment.tpl.php or other template file. And in mytheme_comment_form($form) function add attributes to your textarea:
$form['textareaname']['#attributes'] = array('onkeyup' => 'limit(this,500,’count1′)';
$form['textareaname']['#title'] = "<label for=”text”><strong>Text</strong></label> ¦ Chars left: <span id=”count1″>500</span>"

Categories