Adding Wordpress "Add Media" Button to form in own Plugin - php

I am trying to add my own "Add Media" Button in my own plugin form pages, I created a plugin and I have a form in add-new.php file here is the code:
<div class="wrap">
<h1><?php _e( 'Add Deal', 'webdevs' ); ?></h1>
<form action="" method="post">
<!-- I NEED TO CHANGE THIS TO SHOW "ADD MEDIA BUTTON" -->
<input id="upload_image" type="text" size="36" name="upload_image" value="" />
<input id="upload_image_button" type="button" value="Upload Image" />
<?php wp_nonce_field( 'deal-new' ); ?>
<?php submit_button( __( 'Add Deal', 'webdevs' ), 'primary', 'submit_deal' ); ?>
</form>
How to add the html code and handle it in php
please help
Thnaks

I have created a custom image upload with metabox, you can set below code as per your need.
What you need is to call new WP's thickbox media uploader CSS and JS on your page. you have to modify condition of adding script for plugin page.
Condition to modify if( 'post' !== $typenow ).
What it will do?
It will allow you to open wordpress media uploader and send your selected image url to textbox then you can save the url in post_meta using update_post_meta() or wherever you want to save it. you can get the url from
Supposeable variable :
$content_img = $_POST['content_img'];
Html
<p>
<label><b>Upload Content Image</b></label><br/>
<input class="upload_image" name="content_img" type="text" readonly="readonly" value="<?php echo $content_img ?>"/>
<input type="button" value="Upload" class="button button-primary button-large" onclick="upload_new_img(this)"/>
Remove
</p>
Admin functions.php
// Enqueue script in admin
function my_admin_scripts() {
# Not our screen, bail out
if( 'post.php' !== $hook )
return;
# Not our post type, bail out
global $typenow;
if( 'post' !== $typenow )
return;
wp_enqueue_media('media-upload');
wp_enqueue_media('thickbox');
wp_register_script('my-upload', get_stylesheet_directory_uri().'/js/metabox.js', array('jquery','media-upload','thickbox'));
wp_enqueue_media('my-upload');
}
// Call thickbox CSS
function my_admin_styles() {
wp_enqueue_style('thickbox');
}
add_action('admin_enqueue_scripts', 'my_admin_scripts');
add_action('admin_enqueue_scripts', 'my_admin_styles');
Custom JS metabox.js
function upload_new_img(obj)
{
var file_frame;
var img_name = jQuery(obj).closest('p').find('.upload_image');
if ( file_frame ) {
file_frame.open();
return;
}
file_frame = wp.media.frames.file_frame = wp.media(
{
title: 'Select File',
button: {
text: jQuery( this ).data( 'uploader_button_text' )
},
multiple: false
}
);
file_frame.on('select', function() {
attachment = file_frame.state().get('selection').first().toJSON();
var newwurl = attachment.url.split('/wp-content');
img_name[0].value = '/wp-content'+newwurl[1];
file_frame.close();
// jQuery('.upload_image').val(attachment.url);
});
file_frame.open();
}
function remove_image(obj) {
var img_name;
if (jQuery(obj).closest('p').find('.upload_image').length > 0) {
img_name = jQuery(obj).closest('p').find('.upload_image');
} else {
img_name = jQuery(obj).closest('td').find('.upload_image');
}
if (typeof img_name != "undefined") {
img_name.val('');
}
}

Related

Apply coupon code on Woocommerce checkout page with AJAX

I moved the Woocommerce coupon form by editing the review-order.php based on this method
I would like to know if it's possible to make the coupon code apply with AJAX (without reloading the page) like in the cart page. I don't know where to start, please help.
as per your shared link, if you follow the same means you are using the coupon form inside the checkout form, so you should remove the coupon form tag and then use it.
Copy woocommerce review-order.php and past inside your active then woocommerce folder.
Open review-order.php and past coupon HTML inside table structure like this:
<tr class="coupon_checkout">
<td colspan="2">
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
if ( ! wc_coupons_enabled() ) {
return;
}
?>
<i class="fa fa-plus"></i> REDEEM A PROMO CODE/GIFT VOUCHER
<div class="checkout_coupon" method="post" style="display:none">
<p class="form-row form-row-first">
<input type="text" name="coupon_code" class="input-text" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" id="checkout_coupon_code" value="" />
</p>
<p class="form-row form-row-last">
<input id="checkout_apply_coupon" type="button" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply Coupon', 'woocommerce' ); ?>" />
</p>
</div>
</td>
</tr>
Add jQuery code either your custom.js file or directly on the footer page like this:
<script>
jQuery(document).on('click','#checkout_apply_coupon', function() {
// Get the coupon code
var code = jQuery( '#checkout_coupon_code').val();
var button = jQuery( this );
data = {
action: 'ajaxapplucoupon',
coupon_code: code
};
button.html( 'wait.');
// Send it over to WordPress.
jQuery.post( wc_checkout_params.ajax_url, data, function( returned_data ) {
if( returned_data.result == 'error' ) {
jQuery( 'p.result' ).html( returned_data.message );
} else {
setTimeout(function(){
//reload with ajax
jQuery(document.body).trigger('update_checkout');
button.html( 'Apply');
}, 2000);
console.log( returned_data+code );
}
})
});
</script>
As I have tested on my checkout page it's working perfectly like this:
https://www.loom.com/share/7dfc833895d248f191ba327cf5290403
Optional (if not setup wp_localize_script yet then add into functions.php)
function custom_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/custom.js', array('jquery') ); // optional - if you want to add custom.js then goto theme directory- > js -> and create/add custom.js file
wp_localize_script( 'ajax-script', 'wc_checkout_params', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); // setup ajax call url
}
add_action( 'wp_enqueue_scripts', 'custom_enqueue' );
You can modify the snippet below to match your styles.
Place the coupon form below in review-order.php or include it from a separate file
<form class="checkout_coupon m-0 p-0 border-0 woocommerce-form-coupon grid grid-cols-3" action="<?php echo esc_url(wc_get_cart_url()); ?>" method="post">
<input type="text" name="coupon_code" class="input-text col-span-2" placeholder="<?php esc_attr_e('Coupon code', 'woocommerce'); ?>" id="coupon_code" value=""/>
<button type="submit" class="theme-button-secondary" name="apply_coupon"><i class="fas fa-arrow-right"></i></button>
</form>
<script>
jQuery(document).on('submit', 'form.checkout_coupon', function (e) {
e.preventDefault()
var form = jQuery(this)
form.block({message: null, overlayCSS: {background: '#FFF', opacity: 0.6}})
jQuery.post(wc_checkout_params.ajax_url, {
action: 'ajax_apply_coupon',
coupon_code: form.find('[name="coupon_code"]').val()
}).done(function () {
jQuery(document.body).trigger('update_checkout')
form.unblock()
}).fail(function (data) {
jQuery(document.body).trigger('update_checkout')
form.unblock()
})
})
</script>
If you want to include it from different file use this
add_action('woocommerce_review_order_after_cart_contents', function () {
if (is_checkout()) {
wc_get_template('checkout/coupon.php');
}
});
Add your ajax handler with the coupon logic in your function.php
function ajax_apply_coupon()
{
$coupon_code = null;
if (!empty($_POST['coupon_code'])) {
$coupon_code = sanitize_key($_POST['coupon_code']);
}
$coupon_id = wc_get_coupon_id_by_code($coupon_code);
if (empty($coupon_id)) {
wc_add_notice(__('Sorry, there has been an error.', 'woocommerce'), 'error');
wp_send_json_error(['message' => __('Sorry, there has been an error.', 'woocommerce')], 400);
}
if (!WC()->cart->has_discount($coupon_code)) {
WC()->cart->add_discount($coupon_code);
}
wp_send_json_success(['message' => __('Coupon code applied successfully.', 'woocommerce')], 200);
}
add_action('wp_ajax_ajax_apply_coupon', 'ajax_apply_coupon');
add_action('wp_ajax_nopriv_ajax_apply_coupon', 'ajax_apply_coupon');

Add Item and stay in current page - php, ajax, jquery

I am using google translator, so errors may occur.
My problem: add Item and stay in current page
I tried to use the advice from the link below but I did not succeed :-(
Add Item and stay in current page
Script code:
<?php
if( !defined( 'CUSTOMER_PAGE' ) )
exit;
require_once DIR_SKIN.'_header.php'; // include design of header
?>
<div id="product">
<?php
if( isset( $aData['sName'] ) ){ // displaying product content ?>
<script type="text/javascript">
var sTitle = "<?php echo $aData['sName']; ?>";
var fPrice = Math.abs( "<?php echo $aData['mPrice']; ?>" );
</script><?php
if( isset( $aData['mPrice'] ) || isset( $aData['sAvailable'] ) ){ // displaying box with price, basket and availability - START
echo '<div id="box">';
if( isset( $aData['mPrice'] ) && is_numeric( $aData['mPrice'] ) ){?>
<div id="price"><em><?php echo $lang['Price']; ?>:</em><strong id="priceValue"><?php echo $aData['sPrice']; ?></strong><span><?php echo $config['currency_symbol']; ?></span></div><?php
}
elseif( !empty( $aData['mPrice'] ) ){?>
<div id="noPrice"><?php echo $aData['sPrice']; ?></div><?php
}
if( isset( $aData['sAvailable'] ) ){?>
<div id="available"><?php echo $aData['sAvailable']; ?></div><?php
}
if( isset( $aData['mPrice'] ) && is_numeric( $aData['mPrice'] ) && !empty( $config['basket_page'] ) && isset( $oPage->aPages[$config['basket_page']] ) ){?>
<form action="<?php echo $oPage->aPages[$config['basket_page']]['sLinkName']; ?>" method="post" id="addBasket" class="form">
<fieldset>
<legend><?php echo $lang['Basket_add']; ?></legend>
<input type="hidden" name="iProductAdd" value="<?php echo $aData['iProduct']; ?>" />
<input type="hidden" name="iQuantity" value="1" />
<input type="submit" value="<?php echo $lang['Basket_add']; ?>" class="submit" />
</fieldset>
</form><?php
}
echo '</div>';
} // displaying box with price, basket and availability - END
}
?>
</div>
I've rewritten the code and added it below:
if( isset( $aData['sName'] ) ){ // displaying product content ?>
<script type="text/javascript">
$('#addBasket .submit').click(function() {
var keyValues = {
iProductAdd : $(this).parent().find('input[name="iProductAdd"]').val(),
iQuantity : $(this).parent().find('input[name="iQuantity"]').val()
};
$.post('<?php echo $oPage->aPages[$config['basket_page']]['sLinkName']; ?>', keyValues, function(rsp) {
// make your php script return some xml or json that gives the result
// rsp will be the response
});
return false; // so the page doesn't POST
});
</script>
But still does not work, after clicking the button, the product is added but we do not stay on the same page and go to the basket.
I will be grateful for any help
Adam
Can you try this ?
$('#addBasket .submit').click(function(event) {
event.preventDefault();
var keyValues = {
iProductAdd : $(this).parent().find('input[name="iProductAdd"]').val(),
iQuantity : $(this).parent().find('input[name="iQuantity"]').val()
};
$.post('<?php echo $oPage->aPages[$config['basket_page']]['sLinkName']; ?>', keyValues, function(rsp) {
// make your php script return some xml or json that gives the result
// rsp will be the response
});
return false; // so the page doesn't POST
});
You can use e.preventDefault() instead of return false;
<script type="text/javascript">
$('#addBasket .submit').click(function(e) {
e.preventDefault();
var keyValues = {
iProductAdd : $(this).parent().find('input[name="iProductAdd"]').val(),
iQuantity : $(this).parent().find('input[name="iQuantity"]').val()
};
$.post('<?php echo $oPage->aPages[$config['basket_page']]['sLinkName']; ?>', keyValues, function(rsp) {
// make your php script return some xml or json that gives the result
// rsp will be the response
});
});
Edit 1:
You can do one more thing. Instead of having input type as submit. keep it as button as I noticed you are making JSON manually.
So your input submit can be something like this
<input type="button" value="<?php echo $lang['Basket_add']; ?>" class="submit" />
The event listener is not being added to the button because the button doesn't exist when the script tag is above the form
Either put the script tag after the form or wrap the code in "ready" a call
$(function(){
$('#addBasket .submit').click(function() {
...
})

Wordpress media buttons don't work without item attached to?

I'm currently developing theme settings for my Wordpress theme, i need media buttons in order the user can attach files for the homepage. This files are totally independent.
This medias buttons dont work except when i display a Wordpress editor, can anyone have a solution cleaner than hide the editor with a css hack ?
Thanks in advance!
Personally I did it like this:
in the form
<label for="upload_image" class="upload">
<input id="upload_image" type="text" size="36" name="ad_image" value="<?php echo get_option('ad_image'); ?>" />
<input id="upload_image_button" class="button" type="button" value="Choose Image" />
and then to display the current image selected.
<p><strong>Current Image:</strong>
<?php if (get_option('ad_image')){ echo '<br /><img src="'.get_option('ad_image').'" height="150" width="220"';} else{echo 'None Selected';}?>
</p>
and then enqueue this javascript in the options page
jQuery(document).ready(function($){
var _custom_media = true,
_orig_send_attachment = wp.media.editor.send.attachment;
$('#upload_image_button').click(function(e) {
var send_attachment_bkp = wp.media.editor.send.attachment;
var button = $(this);
var id = button.attr('id').replace('_button', '');
_custom_media = true;
wp.media.editor.send.attachment = function(props, attachment){
if ( _custom_media ) {
$("#"+id).val(attachment.url);
} else {
return _orig_send_attachment.apply( this, [props, attachment] );
};
}
wp.media.editor.open(button);
return false;
});
$('.add_media').on('click', function(){
_custom_media = false;
});
});

Wordpress Submit a form using AJAX

I created a Wordpress plugin to allow my client to create events with the ability to rsvp and pay for an event. I'm confused as to where certain code needs to be placed and how to submit a form to a function that resides within the plugin folder functions file.
At the moment it returns a blank alert.
I am displaying this form on a single event's page:
<div id="rsvpContent">
<form id="Attendevent" action="">
<input id="attend" name="attend" type="checkbox" value="yes" /><label for="attent">Yes, I plan to attend.</label>
</form>
Then, I placed this into the general header.php file:
$("#attend").click(function(){
var form = $("#Attendevent").serialize();
$.ajax({
type:'POST',
data:{"action":"Attending","data": form },
url: "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php",
beforeSend: function(){
alert(form);
},
success: function(data) {
alert(data);
}
});
});
Then, I placed this function into the main functions page within the plugin folder:
function eventAttent() {
$wpdb->show_errors();
if($_POST['attend'] == 'yes') {
$wpdb->insert('wp_event_attendants',
array( 'event_id' => get_the_ID(),'user_id' => $current_user->ID));
echo $wpdb->print_error();
}
}
add_action('wp_ajax_Attending', 'eventAttend');
add_action('wp_ajax_nopriv_Attending', 'eventAttend');
How can this function be called when a user clicks the 'Attending' checkbox?
This link is a very good source for ajaxifying your theme.
Put this code into functions.php in your child theme.
// enqueue your custom js
function my_js_method() {
// for jquery ui
wp_enqueue_style( 'jqueryUI_style', get_stylesheet_directory_uri() . '/customCSS/jquery-ui.css' );
wp_enqueue_script(
'handleFormAjax-script',
get_stylesheet_directory_uri() . '/handleFormAjax.js',
array( 'jquery' )
);
// add the appropriate hook
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'handleFormAjax-script', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
// AJAX handler snippet
function myHandlerMethod(){
if (is_admin())
echo "woow working like a charm";
die();
}
//add the hooks for your handler function
add_action('wp_ajax_myHandlerMethod', 'myHandlerMethod');
// for users who are not logged in
add_action('wp_ajax_nopriv_myHandlerMethod', 'myHandlerMethod');
In addition to that your form should look like this.
<form id="assetForm" action= "/wp-admin/admin-ajax.php" method="post">
<input type="hidden" name="action" value="myFunction"/>
<button id="sbmBtn">SUBMIT </button>
</form>
and lastly, you js function should address the handler function that you defined in functions.php
var data = jQuery("#myForm :input").serializeArray();
jQuery.post(jQuery("#myForm").attr("action"),data, function(info) {
// success code ;
});
try with this code. this is my tested code. working fine with me .. but it will not process FILE upload.
HTML
<form id="form_name" name="form_name" >
<span id='errfrmMsg' style='margin:0 auto;'></span>
//form attributes just as input boxe.
<input type="hidden" name="action" value="anyName" />
<input id="submit_button" onclick="submit_form();" type="button" value="Send" />
</form>
j Query
function submit_form()
{
jQuery.post(the_ajax_anyName.ajaxurl_anyName,
jQuery("#form_name").serialize(),
function(response_from_the_action_function){
jQuery("#errfrmMsg").html(response_from_the_action_function).css({"display":"block"});
}
);
}
Php code in functions.php
wp_register_script("ajax-anyName", get_bloginfo('template_directory')."/js/custom_js.js", array( "jquery"));
wp_enqueue_script('ajax-anyName');
wp_localize_script("ajax-anyName","the_ajax_anyName", array("ajaxurl_anyName" => admin_url("admin-ajax.php")));
// add actions
add_action( "wp_ajax_anyName", "ajax_action_anyName" );
add_action( "wp_ajax_nopriv_anyName", "ajax_action_anyName" );
function ajax_action_anyName(){
//Form processing code in PHP
}

Integrating image upload box in WordPress widget

I am working on a small WordPress widget and I am trying to set it up where the user can upload an image. So far, the necessary scripts are loading but when I click the "Media Library Image" button the image uploader doesn't pop up.
Here is my javascript file:
jQuery(document).ready(function($) {
var formfield = null;
$('#upload_image_button').click(function() {
$('html').addClass('Image');
formfield = $('#wp-ss-image').attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
// user inserts file into post. only run custom if user started process using the above process
// window.send_to_editor(html) is how wp would normally handle the received data
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html){
var fileurl;
if (formfield != null) {
fileurl = $('img',html).attr('src');
$('#wp-ss-image').val(fileurl);
tb_remove();
$('html').removeClass('Image');
formfield = null;
} else {
window.original_send_to_editor(html);
}
};
});
Here is are my functions to call the scripts:
add_action('admin_print_scripts-widgets.php', 'wp_ss_image_admin_scripts');
function wp_ss_image_admin_scripts() {
wp_enqueue_script( 'wp-ss-image-upload', plugins_url( '/WP-Simple-Social/wp-simple-social-image.js' ), array( 'jquery','media-upload','thickbox' ) );
}
add_action('admin_print_styles-widgets.php', 'wp_ss_admin_styles');
function wp_ss_admin_styles() {
wp_enqueue_style( 'thickbox' );
}
And here is the html to display the input box and image upload button:
<p>Upload Photo: <input id="wp-ss-image" class="widefat" type="text" size="75" name="<?php echo $this->get_field_name( 'image' ); ?>" value="<?php echo esc_url( $image ); ?>" />
<input id="upload_image_button" type="button" value="Media Library Image" class="button-secondary" />
Since all of the necessary files/scripts are loading, could this be a jQuery problem?
If there is any other additional info that would help out please let me know. Thanks for the help.
Best way I found was using live() method even if it deprecated to on() profit.
Worked
jQuery(document).ready(function($) {
$("#testage").live("click", function() {
alert("CLICK!");
});
});
Didn't work
jQuery(document).ready(function($) {
$("#testage").on("click", function() {
alert("CLICK!");
});
});
If anybody has an explication I would be grateful.

Categories