Wordpress: Make plugin option to modify jquery - wordpress

I am trying to add plugin option to update jquery but don't have any idea how to do that. I am adding jquery using wp_enqueue_script() and so it is not allowing to add php function ( get_option() ) to the jquery code. Please help me to resolve this.
Jquery code:
jQuery(document).ready(function(){
$cnt = 0;
jQuery('#add-photo-button').click(function(){
if($cnt == 3){ // where 3 should replaced with plugin option function/varible
jQuery('#add-photo-button').prop('disabled', true);
jQuery('#add-photo-button').addClass('disabled');
}
$cnt++;
var current_count = jQuery('input[type="file"]').length;
//var next_count = current_count + 1;
jQuery('#file-upload').prepend('<p><input type="file" name="photo[]" /></p>');
});
});

Please see the wp_localize_script() function.
You must enqueue your script, then localize (or rather: pass the data as inline JavaScript) the data you want to reference in the JavaScript and lastly update your script to reference the newly localized global object. Please see my example below.
Example
1- Enqueue your script in your plugin, then "localize" the variable data using wp_localize_script(). Make sure you use the same handle for both function calls.
<?php
// !! Edit the variables below to suit your plugin
$add_photo_button_handle = 'some_handle';
$add_photo_button_js = plugins_url( '/add_photo_button.js', __FILE__ );
$photo_num = get_option( 'add_photo_button_cnt' ); // Here you fetch the option data.
// Enqueue your script
wp_enqueue_script( $add_photo_button_handle, $add_photo_button_js );
// Set the data you want to pass to your script here
$data = array( 'photo_button_cnt' => $photo_num );
// Localize the script, the 'photo_button_cnt' value will now be accessible as a property in the global 'add_photo_button' object.
wp_localize_script( $add_photo_button_handle, 'add_photo_button', $data );
?>
2- Change your script to reference the localized object
<script type="text/javascript">
jQuery(document).ready(function(){
$cnt = 0;
jQuery('#add-photo-button').click(function(){
//============================================
// See how we access the localized object.
//============================================
if($cnt == add_photo_button.photo_button_cnt ){
jQuery('#add-photo-button').prop('disabled', true);
jQuery('#add-photo-button').addClass('disabled');
}
$cnt++;
var current_count = jQuery('input[type="file"]').length;
//var next_count = current_count + 1;
jQuery('#file-upload').prepend('<p><input type="file" name="photo[]" /></p>');
});
});
</script>

Related

How to add a nonce to an inline script in WordPress

I'm trying to add a nonce to the inline scripts inserted in WordPress by wp_add_inline_script and wp_localize_script, but I can't figure out how to do it. It looks there are no WordPress filters for that. My goal is to have a nonce for inline scripts, so I can define a Content Security Policy that would not break common plugins that insert inline scripts. At the end the result should be something that looks like:
<script type="text/javascript" nonce="xxxxxxxxxx">....</script>
where xxxxxxxx is the nonce.
Do you have any ideas?
As the HTML for inline scripts are generated by the WordPress code
sprintf( "<script type='text/javascript'>\n%s\n</script>\n", ... )
you cannot add an attribute to the HTML script element using wp_add_inline_script() as <script type='text/javascript'> is hard coded.
However, the filter 'script_loader_tag' will allow you to change the HTML for script elements just before it is outputted by WordPress.
Note that the filter 'script_loader_tag' will not be applied to script elements added by calling wp_localize_script() since these are outputted by the WordPress code:
echo "<script type='text/javascript'>\n"; // CDATA and type='text/javascript' is not needed for HTML 5
echo "/* <![CDATA[ */\n";
echo "$output\n";
echo "/* ]]> */\n";
echo "</script>\n";
Since these are echoed and <script type='text/javascript'> is hard coded you cannot add an attribute to the HTML script elements of wp_localize_script().
Try to use wp_enqueue_scripts hook
function my_special_inline_script() {
?>
<script>
// your JS code
</script>
<?php
}
add_action( 'wp_enqueue_scripts', 'my_special_inline_script', 1, 1 );
or
function theme_prefix_enqueue_script() {
wp_add_inline_script( 'jquery', 'jQuery(document).ready(function(){});' );
}
add_action( 'wp_enqueue_scripts', 'theme_prefix_enqueue_script' );
Bit late to the party but I just faced this exact problem for the same reasons.
I solved it for wp_add_inline_script by a bit of simple str_replace action.
add_filter( 'script_loader_tag', 'add_nonce_to_script_tag', 10, 3 );
function add_nonce_to_script_tag( $tag, $handle, $src ) {
// Check the $handle and respond accordingly
if ( $handle === 'my-script' ) {
$nonce_value = wp_create_nonce('my__script__nonce'); // or ref to an existing nonce
$replace = sprintf("javascript' nonce='%s'>", $nonce_value );
$tag = str_replace( "javascript'>", $replace, $tag);
}
return $tag;
}
// Then... $data is the inline JS from wherever
wp_add_inline_script('my-script', $data, 'before');
Once the inline script loads, I am seeing the script tag output with a nonce attribute. This is working fine with my Content-Security-Policy.
Check this out
"WordPress 5.7 adds a handful of new functions that enables passing attributes, such as async or nonce"

In wordpress to mark required fields in Add New Post page

in WP 4.2 opening Add New Post page and without editing any fields, clicking on "Publish" button page is submitted and reopened, but no any of fields are marked with red background color as required.
How to make it? Seems, that is original behauvior of this page.
I want it to work like editor of categories, when in similar situation field name is marked with red background color as required.
Also I added several fields to New Post page using register_post_type function and I aslo want to marked with red background color as required. Which is the best way for this?
Thanks!
You can call your jquery validation by your self using below code,
Add this code in theme's functions.php and custom.js in your theme js folder
add_action( 'admin_print_scripts-post-new.php', 'custom_admin_script', 11 );
add_action( 'admin_print_scripts-post.php', 'custom_admin_script', 11 );
function custom_admin_script() {
global $post_type;
// Post type = "post" or "page" you can load script wheater it is post or page , if page then change 'post' to 'page' in below condition
if( 'post' == $post_type )
wp_enqueue_script( 'custom-admin-script', get_stylesheet_directory_uri() . '/js/custom.js' );
}
custom.js
jQuery(document).ready(function ($) {
if ($("#post").length > 0) {
var frm = true;
$("#publish").click(function () {
var title = $("#title").val();
var excerpt = $("#excerpt").val();
// your custom field variable goes here
if (jQuery.trim(title) == "" || jQuery.trim(excerpt) == "") {
frm = false;
}
if (frm == false) {
$("#publish").prop('disabled', true);
} else {
$("#publish").prop('disabled', false);
}
});
}
});

Global variable is not working between functions

i am creating plugin for my project. i want to create one page when plugin gets activate and same way i want to delete that page when plugin gets deactivate... i am able to create page but i am facing problem while deleting page...
my code is
global $page_id;
register_activation_hook(__FILE__,'createPage');
register_deactivation_hook(__FILE__, 'dropPage');
function createPage()
{
global $page_id;
$page['post_type'] = 'page';
$page['post_content'] = 'hello this page created by plugin';
$page['post_status'] = 'publish';
$page['post_title'] = 'dpage';
$page_id = wp_insert_post ($page);
}
function dropPage()
{
global $page_id;
wp_delete_page($page_id);
}
it's not deleting page... if i give wp_delete_post('116') then it's working fine... i have assigning page id in global variable then also i am not able to retrieve it..
can any one suggest me how to do it?
Thanks in advance
the global $page_id you're adding will only contain the page ID when you're activating the plugin. To store the page ID, use the Options API.
register_activation_hook(__FILE__,'createPage');
register_deactivation_hook(__FILE__, 'dropPage');
function createPage()
{
$page['post_type'] = 'page';
$page['post_content'] = 'hello this page created by plugin';
$page['post_status'] = 'publish';
$page['post_title'] = 'dpage';
$page_id = wp_insert_post ($page);
update_option('the_page_id_i_created', $page_id );
}
function dropPage()
{
if( get_option('the_page_id_i_created') ){
wp_delete_page( get_option('the_page_id_i_created') );
}
}

Text formatting not working with qTranslate plugin

I am creating a multilingual website using wordpress as CMS.
i am using qTranslate plugin for multi language support. As soon as i enable the plugin, all formatting of text is lost. i.e. all paragraphs in the editor are merged into a single paragraph.
I have enabled this option in settings: "WordPress should correct invalidly nested XHTML automatically" but there is no change.
Any suggestions please?
Add this code at the end of wp-content\themes\your-theme-name\functions.php:
//************************** PATCH START *****************************
// Fix for qTranslate plugin (that does not retain formatting in pages)
if('html' != wp_default_editor()) {
remove_filter('the_editor_content', 'wp_richedit_pre');
add_filter('the_editor_content', 'wp_htmledit_pre');
}
remove_filter( 'the_content', 'wpautop' );
if ( ! function_exists('tmce_replace') ) {
function tmce_replace() {
$tadv_options = get_option('tadv_options', array());
$tadv_plugins = get_option('tadv_plugins', array());
?>
<script type="text/javascript">
if ( typeof(jQuery) != 'undefined' ) {
jQuery('body').bind('afterPreWpautop', function(e, o){
o.data = o.unfiltered
.replace(/caption\]\ +?<\/object>/g, function(a) {
return a.replace(/[\r\n]+/g, ' ');
});
}).bind('afterWpautop', function(e, o){
o.data = o.unfiltered;
});
}
</script>
<?php
}
add_action( 'after_wp_tiny_mce', 'tmce_replace' );
}
function teslina_tinymce_config( $init ) {
$init['remove_linebreaks'] = false;
$init['apply_source_formatting'] = true;
$init['preformatted'] = true;
$init['remove_redundant_brs'] = false;
return $init;
}
add_filter('tiny_mce_before_init', 'teslina_tinymce_config');
//************************** PATCH END *******************************
write simple post in html mode to test like this :
<p>lorem</p>
<p>ipsum</p>
There is filter in wordpress to format text (plugin, or functions.php) try to find them, else try another plugin like Polylang.
I found a solution here:
http://www.teslina.com/en/748/wordpress/qtranslate-code-syntax-bugfix/
However i suspect that the code added in plugin will be removed when it's updated.

trouble adding jQuery UI to Wordpress admin page

I'm attempting to add a datepicker to a custom meta box in wordpress. If I enqueue the script like so
// add stylesheets for date picker
add_action('admin_print_styles', 'add_datepicker_styles');
function add_datepicker_styles() {
global $post;
$styleFile = get_bloginfo("template_url").'/refactored-datepicker/css/ui-lightness/jquery-ui-1.8.17.custom.css';
if(file_exists($styleFile) && $post->post_type == 'show') {
wp_enqueue_style("datepicker-css", $styleFile);
}
}
// add javascript for date picker
add_action('admin_print_scripts', 'add_datepicker_js');
function add_datepicker_js() {
global $post;
$jsFile = get_bloginfo("template_url").'/refactored-datepicker/js/jquery-ui-1.8.17.custom.min.js';
if(file_exists($jsFile) && $post->post_type == 'show') {
wp_enqueue_script("datepicker-js", $jsFile);
}
}
// add date picker init
add_action('admin_head', 'add_datepicker_init');
function add_datepicker_init() {
global $post;
if($post->post_type == 'show') {
echo "<script type='text/javascript'>jQuery(document).ready(function() { jQuery('#show_date').datepicker(); });</script>";
}
}
I get an error that jQuery('#show_date').datepicker(); is not a function. When I check the processed source code I see that jQuery is loaded by default but the style and jQuery UI script are not loaded at all. The code attached to the admin_head hook loads fine and if I echo the script and styles in this function it works the way I want it to.
// add date picker init
add_action('admin_head', 'add_datepicker_init');
function add_datepicker_init() {
global $post;
if($post->post_type == 'show') {
echo "<link rel='stylesheet' type='text/css' href='".get_bloginfo("template_url").'/refactored-datepicker/css/ui-lightness/jquery-ui-1.8.17.custom.css'."' />";
echo "<script type='text/javascript' src='".get_bloginfo('template_url').'/refactored-datepicker/js/jquery-ui-1.8.17.custom.min.js'."'></script>";
echo "<script type='text/javascript'>jQuery(document).ready(function() { jQuery('#show_date').datepicker(); });</script>";
}
}
So is it a problem with the wp_enqueue_style/script() functions or with the add_action hooks? I'm new to wordpress so I'm not really sure how to troubleshoot this. I've done a google search and everywhere I go the code looks like mine. Also if you are wondering the paths to the files are correct.
Can anyone think of a solution to my problem? Is it wrong to just echo the script and styles or should I enqueue them?
Thanks!
EDIT:
file_exists($jsFile) returns false. if I remove the conditional check for the file the code works.. But why? how else can you check for a file that exists using a url beginning with http:// as opposed to a local file path?
If you want to get a local path for your theme, you can use get_theme_root():
$styleFile = get_theme_root().'/refactored-datepicker/css/ui-lightness/jquery-ui-1.8.17.custom.css';
if(file_exists($styleFile) && $post->post_type == 'show') {
From php.net/file_exists:
this code here is in case you want to check if a file exists in
another server:
<?php function fileExists($path){
return (#fopen($path,"r")==true); } ?>
unfortunately the file_exists can't reach remote servers, so I used
the fopen function.

Resources