WooCommerce Product per page Select option without reload - wordpress

hi I'm trying without reload Woo-commerce Shop page product per page but its reload of selected number...
Now it's working but page reload then work I need to without reload of shop page
anybody help me
add_action('wp_head','theme_ajaxurl');
function theme_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action( 'wp_ajax_nopriv_dl_sort_by_page', 'woocommerce_catalog_per_page_ordering' );
add_action( 'wp_ajax_dl_sort_by_page', 'woocommerce_catalog_per_page_ordering' );
function woocommerce_catalog_per_page_ordering() {
?>
<form action="" method="POST" name="results">
<select name="woocommerce-sort-by-columns" id="woocommerce-sort-by-columns" class="sortby">
<?php
// This is where you can change the amounts per page that the user will use feel free to change the numbers and text as you want, in my case we had 4 products per row so I chose to have multiples of four for the user to select.
$shopCatalog_orderby = apply_filters('woocommerce_sortby_page', array(
'' => __('Products per page', 'woocommerce'),
'8' => __('8 per page', 'woocommerce'),
'16' => __('16 per page', 'woocommerce'),
'32' => __('32 per page', 'woocommerce'),
'-1' => __('View All', 'woocommerce'),
));
foreach ( $shopCatalog_orderby as $sort_id => $sort_name )
echo '<option value="' . $sort_id . '" ' . selected( $_SESSION['sortby'], $sort_id, false ) . ' >' . $sort_name . '</option>';
?>
</select>
</form>
<?php // Adrian's code
if (isset($_POST['woocommerce-sort-by-columns']) && (($_COOKIE['shop_pageResults'] <> $_POST['woocommerce-sort-by-columns']))) {
$currentProductsPerPage = $_POST['woocommerce-sort-by-columns'];
} else {
$currentProductsPerPage = $_COOKIE['shop_pageResults'];
}
?>
<script type="text/javascript">
jQuery('select.sortby>option[value="<?php echo $currentProductsPerPage; ?>"]').attr('selected', true);
</script>
<?php
}
// now we set our cookie if we need to
function dl_sort_by_page($count) {
if (isset($_COOKIE['shop_pageResults'])) { // if normal page load with cookie
$count = $_COOKIE['shop_pageResults'];
}
if (isset($_POST['woocommerce-sort-by-columns'])) { //if form submitted
setcookie('shop_pageResults', $_POST['woocommerce-sort-by-columns'], time()+1209600, '/', 'yourdomain.com', false); //this will fail if any part of page has been output- hope this works!
$count = $_POST['woocommerce-sort-by-columns'];
}
// else normal page load and no cookie
return $count;
}
add_filter('loop_shop_per_page','dl_sort_by_page');
Script Code
<script>
jQuery( document ).on( 'change', '#woocommerce-sort-by-columns', function(event) {
event.preventDefault();
var post_id = jQuery('select.sortby').val();
jQuery.ajax({
url : ajaxurl,
type : 'POST',
data : {
action : 'dl_sort_by_page'
},
success : function( response ) {
alert('ok');
}
});
})
</script>

Related

How can get the checkout field value and hidden order button in woocommerce?

I have payment needed to wait for JS callback token, so on the checkout page, the flow will have the customer check the token button, then click and get the token will apply to the custom field,
in the end, if the custom field is not empty show the order button.
custom field
function techiepress_payleo_description_fields( $description, $payment_id ) {
if( 'payleos' !== $payment_id) {
return $description;
};
// $json = json_encode(WC()->cart);
ob_start();
echo '<div id="Payment">'; // it will create get token button
echo '</div>';
woocommerce_form_field( 'payment_number', array(
'type' => 'text',
'label' => __("credit card", "payleo_payment_plus"),
'required' => true,
),'');
$description .= ob_get_clean();
return $description;
}
hidden order button
add_filter('woocommerce_order_button_html', 'remove_place_order_button_for_specific_payments' );
function remove_place_order_button_for_specific_payments( $button ) {
// HERE define your targeted payment(s) method(s) in the array
$targeted_payments_methods = array('payleos');
$chosen_payment_method = WC()->session->get('chosen_payment_method'); // The chosen payment
// For matched payment(s) method(s), we remove place order button (on checkout page)
if( in_array( $chosen_payment_method, $targeted_payments_methods ) && ! is_wc_endpoint_url() ) {
$button = '';
}
return $button;
}
// jQuery - Update checkout on payment method change
add_action( 'wp_footer', 'custom_checkout_jquery_script' );
function custom_checkout_jquery_script() {
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?>
<script type="text/javascript">
jQuery( function($){
$('form.checkout').on('change', 'input[name="payment_method"]', function(){
$(document.body).trigger('update_checkout');
});
});
</script>
<?php
endif;
}
I would like to know how can show the place order button when the custom field has value?

Multiple select product using select2 for wordpress plugin option page

I am trying to implement multiple select product using select2 . the list come up using getproductsearch this ajax action i did earlier but i failed to save it. I did this feature before for post-meta and product-category but failed for plugin option page. I am not sure what i am doing wrong.
please help.
class FeatureSale {
private $feature_sale_options;
public function __construct() {
add_action( 'admin_menu', array( $this, 'feature_sale_add_plugin_page' ) );
add_action( 'admin_init', array( $this, 'feature_sale_page_init' ) );
}
public function feature_sale_add_plugin_page() {
add_submenu_page(
'exclutips-settings',
'Feature & Sale', // page_title
'Feature & Sale', // menu_title
'manage_options', // capability
'feature-sale', // menu_slug
array( $this, 'feature_sale_create_admin_page' ) // function
);
}
public function feature_sale_create_admin_page() {
$this->feature_sale_options = get_option( 'feature_sale_option_name' ); ?>
<div class="wrap">
<div class="catbox-area-admin" style="width: 500px;background: #fff;padding: 27px 50px;">
<h2>Feature & Sale</h2>
<p></p>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php
settings_fields( 'feature_sale_option_group' );
do_settings_sections( 'feature-sale-admin' );
submit_button();
?>
</form>
</div>
</div>
<?php }
public function feature_sale_page_init() {
register_setting(
'feature_sale_option_group', // option_group
'feature_sale_option_name', // option_name
array( $this, 'feature_sale_sanitize' ) // sanitize_callback
);
add_settings_section(
'feature_sale_setting_section', // id
'', // title
array( $this, 'feature_sale_section_info' ), // callback
'feature-sale-admin' // page
);
add_settings_field(
'vpm_sale_product', // id
'VPM Sale Product', // title
array( $this, 'vpm_sale_product_callback' ), // callback
'feature-sale-admin', // page
'feature_sale_setting_section' // section
);
add_settings_field(
'vpm_featured_product', // id
'VPM Featured Product', // title
array( $this, 'vpm_featured_product_callback' ), // callback
'feature-sale-admin', // page
'feature_sale_setting_section' // section
);
}
public function feature_sale_sanitize($input) {
$sanitary_values = array();
if ( isset( $input['vpm_sale_product'] ) ) {
$sanitary_values['vpm_sale_product'] = $input['vpm_sale_product'];
}
if ( isset( $input['vpm_featured_product'] ) ) {
$sanitary_values['vpm_featured_product'] = $input['vpm_featured_product'];
}
return $sanitary_values;
}
public function feature_sale_section_info() {
}
//Output the HTML for the metabox.
public function vpm_sale_product_callback() {
global $post;
// Nonce field to validate form request came from current site
wp_nonce_field( basename( __FILE__ ), 'vpm_sale_product_nonce' );
$html = '';
// always array because we have added [] to our <select> name attribute
$feature_sale_options = get_option( 'feature_sale_option_name' ); // Array of All Options
$vpm_sale_product = $feature_sale_options['vpm_sale_product'];
$html .= '<p><select id="vpm_sale_product" name="vpm_sale_product[]" multiple="multiple" style="width:99%;max-width:25em;">';
if( $vpm_sale_product ) {
foreach( $vpm_sale_product as $post_id ) {
$title = get_the_title( $post_id );
// if the post title is too long, truncate it and add "..." at the end
$title = ( mb_strlen( $title ) > 50 ) ? mb_substr( $title, 0, 49 ) . '...' : $title;
$html .= '<option value="' . $post_id . '" selected="selected">' . $title . '</option>';
}
}
$html .= '</select></p>';
echo $html;
//==========================================
}
//* Output the HTML for the metabox.
public function vpm_featured_product_callback() {
global $post;
// Nonce field to validate form request came from current site
wp_nonce_field( basename( __FILE__ ), 'vpm_featured_product_nonce' );
$html = '';
// always array because we have added [] to our <select> name attribute
$feature_sale_options = get_option( 'feature_sale_option_name' ); // Array of All Options
$vpm_featured_product = $feature_sale_options['vpm_featured_product'];
$html .= '<p><select id="vpm_featured_product" name="vpm_featured_product[]" multiple="multiple" style="width:99%;max-width:25em;">';
if( $vpm_featured_product ) {
foreach( $vpm_featured_product as $post_id ) {
$title = get_the_title( $post_id );
// if the post title is too long, truncate it and add "..." at the end
$title = ( mb_strlen( $title ) > 50 ) ? mb_substr( $title, 0, 49 ) . '...' : $title;
$html .= '<option value="' . $post_id . '" selected="selected">' . $title . '</option>';
}
}
$html .= '</select></p>';
echo $html;
echo $vpm_featured_product;
//==========================================
?>
<script>
(function ($) {
'use strict';
$(function () {
//--------------------------------------------------------------------------
// multiple select with AJAX search
$('#vpm_featured_product,#vpm_sale_product').select2({
ajax: {
url: ajaxurl, // AJAX URL is predefined in WordPress admin
dataType: 'json',
delay: 250, // delay in ms while typing when to perform a AJAX search
data: function (params) {
return {
q: params.term, // search query
action: 'getproductsearch' // AJAX action for admin-ajax.php
};
},
processResults: function( data ) {
var options = [];
if ( data ) {
// data is the array of arrays, and each of them contains ID and the Label of the option
$.each( data, function( index, text ) { // do not forget that "index" is just auto incremented value
options.push( { id: text[0], text: text[1] } );
});
}
return {
results: options
};
},
cache: true
},
minimumInputLength: 3 // the minimum of symbols to input before perform a search
});
//----------------------------------------------------------------------------------------
});
})(jQuery);
</script>
<?php
}
}
if ( is_admin() )
$feature_sale = new FeatureSale();
The problem is that these select tags are not using the correct name value:
<select id="vpm_sale_product" name="vpm_sale_product[]"...>
<select id="vpm_featured_product" name="vpm_featured_product[]"...>
And the proper name values are: (based on your register_setting() call)
<select id="vpm_sale_product" name="feature_sale_option_name[vpm_sale_product][]"...>
<select id="vpm_featured_product" name="feature_sale_option_name[vpm_featured_product][]"...>
And although after correcting the above issue, the form data would be saved properly, the fifth parameter (i.e. the menu/page slug) passed to add_submenu_page() should match the fourth parameter passed to add_settings_section() and add_settings_field(), and also the one passed to do_settings_sections(). In your add_submenu_page() call, the menu/page slug is feature-sale, but with the other three functions, you set it to feature-sale-admin.
And using wp_nonce_field() is recommended, but in your case, it's not necessary since you're submitting to wp-admin/options.php. Unless of course, you want to check that prior to WordPress saving the options. But even so, I believe one nonce field is good. :)

WordPress Update custom post status by clicking custom link in admin

i have a site where i get posts from users, those posts save in WP as a custom post with status pending,
Admin have custom link in that custom post type page Approve | Reject
Approve should change post status to Public
Reject Should change post status to trash/del
can anyone tell any hook to anything which i can run to change post status from backend by clicking these custom links
the code of approve | reject button if anyone want to see
add_filter( 'manage_dream_posts_columns', 'smashing_filter_posts_columns' );
function smashing_filter_posts_columns( $columns ) {
$columns['decision'] = __( 'Decision Pending', 'rima' );
return $columns;
}
add_action( 'manage_dream_posts_custom_column', 'smashing_dream_column', 10, 2);
function smashing_dream_column( $column, $post_id ) {
if ( 'decision' === $column ) {
if (get_post_status ( $post_id ) == 'pending') {
echo '<div class="decision">ApproveReject</div>';
}
else {
echo '<div class="decision"><span class="dapprove">Approved</span></div>';
}
}
}
You could do something like this - it's a bit hacky and uses jQuery but is a quick fix for your issue using an Ajax method so it all works realtime with your admin screen. You can approve/reject multiple posts without any page reloads, including some colour feedback to let you know what's happening.
You need to add 2 new actions:
add_action( 'wp_ajax_set_post_status', 'set_post_status_ajax_handler' );
add_action( 'admin_footer', 'set_post_status_js' );
Then add these functions:
function set_post_status_js()
{
$nonce = wp_create_nonce('set_post_status');
$ajax_url = admin_url('admin-ajax.php'); ?>
<script type="text/javascript">
(function($){
$(document).ready(function(){
$('.decision a').click(function(event){
event.preventDefault();
$.post( "<?= $ajax_url; ?>", {
nonce: "<?= $nonce; ?>",
action: 'set_post_status',
post_id: $(this).data('post_id'),
status: $(this).data('status'),
}, function(data){
if (data.ok) {
var postStateLabel = (data.status === 'publish') ? '<span style="color: #009900;">Approved</span>' : '<span style="color: #990000;">Rejected</span>';
$('#post-' + data.id)
.css('background', data.status === 'publish' ? '#EEFFEE' : '#FFEEEE')
.find('.post-state').html( postStateLabel );
}
});
});
});
})(jQuery)
</script>
<?php
}
And
function set_post_status_ajax_handler()
{
$nonce = $_POST['nonce'];
if ( ! wp_verify_nonce( $nonce, 'set_post_status' ) )
die ( 'Not permitted');
// Extract the vars from the Ajax request
$post_id = $_POST['post_id'];
$status = $_POST['status'];
// Now update the relevant post
$post_id = wp_update_post([
'ID' => $post_id,
'post_status' => $status,
], true);
// make sure it all went OK
if (is_wp_error($post_id))
{
$response = [
'ok' => false,
];
} else
{
$response = [
'ok' => true,
'id' => $post_id,
'status' => $status,
];
}
// Return the response
wp_send_json( $response );
}
Finally, you need to change your Approve / Reject links to this HTML:
echo '
<div class="decision">
Approve
Reject
</div>';
Hopefully that will get you sorted. Cheers.

Add link to image with Add media

function tshirt_gif_text() {
woocommerce_wp_text_input(
array(
'id' => 'gif_tshirt',
'label' => __( 'GIF T-Shirt', 'woocommerce' ),
'placeholder' => 'http://',
'desc_tip' => 'true',
'description' => __( 'Them GIF links.', 'woocommerce' ),
'value' => get_post_meta( get_the_ID(), 'gif_tshirt', true )
)
);
}
add_action( 'woocommerce_product_options_advanced', 'tshirt_gif_text' );
function tshirt_gif_text_save( $post_id ) {
// update_post_meta( $post_id, 'gif_tshirt', $checkbox );
if (isset($_POST['gif_tshirt'])){
update_post_meta( $post_id, 'gif_tshirt', $_POST['gif_tshirt'], false );
}
if (!isset($_POST['gif_tshirt'])){
delete_post_meta( $post_id, 'gif_tshirt');
}
}
add_action( 'woocommerce_process_product_meta', 'tshirt_gif_text_save' );
I made a custom text field to add a link to a image. I'd like to use the Media uploader to upload or choose an image from the existent ones and update the "gif_tshirt" post meta with the link, but I don't know exactly how to start.
Add my media
I think as a button I can use this one.
And this is the JS
jQuery(function($) {
$(document).ready(function(){
$('#insert-my-media').click(open_media_window);
});
function open_media_window() {
if (this.window === undefined) {
this.window = wp.media({
title: 'Insert a media',
library: {type: 'image'},
multiple: false,
button: {text: 'Insert'}
});
var self = this; // Needed to retrieve our variable in the anonymous function below
this.window.on('select', function() {
var first = self.window.state().get('selection').first().toJSON();
wp.media.editor.insert('[myshortcode id="' + first.id + '"]');
});
}
this.window.open();
return false;
}
});
But it inserts this in the main description, how can i choose the destination?
I did it!
add_action('plugins_loaded', function(){
if($GLOBALS['pagenow']=='post.php'){
add_action('admin_print_scripts', 'my_admin_scripts');
add_action('admin_print_styles', 'my_admin_styles');
}
});
function my_admin_scripts(){
wp_enqueue_script('jquery');
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
}
function my_admin_styles(){
wp_enqueue_style('thickbox');
}
add_action(
'add_meta_boxes',
function(){
add_meta_box(
'my-metaboxx1', // ID
'Hover MP4 Catalog', // Title
'func99999', // Callback (Construct function)
get_post_types(), //screen (This adds metabox to all post types)
'side', // Context
'core'
);
},
999
);
function func99999($post){
$url =get_post_meta($post->ID,'gif_tshirt', true); ?>
<label for="video_URL">
<input id="video_URL" type="text" name="video_URL" value="<?php echo $url;?>" />
<input id="upload_video_button" class="button" type="button" value="Choose a Video" />
<br />Choose a video from the media library then, update your post/page to save it.<br /><br />
<?php
if ($url != "") {
?>
<video class="video" controls>
<source src="<?php echo $url;?>" type="video/mp4" id="vidsrc">
Your browser does not support HTML5 video.
</video>
<?php
}
?>
</label>
<script>
jQuery(document).ready(function($){
$('#video-metabox.postbox').css('margin-top','30px');
var custom_uploader;
$('#upload_video_button').click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose a Video',
button: {
text: 'Choose a Video'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$('#video_URL').val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
});
</script>
<?php
}
add_action( 'save_post', function ($post_id) {
if (isset($_POST['video_URL'])){
update_post_meta($post_id, 'gif_tshirt',$_POST['video_URL']);
}
});

I have created gallery metabox but it does not work

here is the code which I got from github page:
define('MY_POST_TYPE', 'my');
define('MY_POST_SLUG', 'gallery');
function my_register_post_type () {
$args = array (
'label' => 'Gallery',
'supports' => array( 'title', 'excerpt' ),
'register_meta_box_cb' => 'my_meta_box_cb',
'show_ui' => true,
'query_var' => true
);
register_post_type( MY_POST_TYPE , $args );
}
add_action( 'init', 'my_register_post_type' );
function my_meta_box_cb () {
add_meta_box( MY_POST_TYPE . '_details' , 'Media Library', 'my_meta_box_details', MY_POST_TYPE, 'normal', 'high' );
}
function my_meta_box_details () {
global $post;
$post_ID = $post->ID; // global used by get_upload_iframe_src
printf( "<iframe frameborder='0' src=' %s ' style='width: 100%%; height: 400px;'> </iframe>", get_upload_iframe_src('media') );
}
It shows my gallery page and media up-loader section on that page nicely, but there is no insert into post button inside that uploader and I am unable to insert image to that post. Additionally, If I upload image from my computer it has insert into post button, once I click upon that button page all my media up-loader screen disappears and nothing happens ? what's wrong with my code or approach please
You are missing editor in your supports:
define('MY_POST_TYPE', 'my');
define('MY_POST_SLUG', 'gallery');
function my_register_post_type () {
$args = array (
'label' => 'Gallery',
'supports' => array( 'title', 'excerpt', 'editor' ),
'register_meta_box_cb' => 'my_meta_box_cb',
'show_ui' => true,
'query_var' => true
);
register_post_type( MY_POST_TYPE , $args );
}
add_action( 'init', 'my_register_post_type' );
function my_meta_box_cb () {
add_meta_box( MY_POST_TYPE . '_details' , 'Media Library', 'my_meta_box_details', MY_POST_TYPE, 'normal', 'high' );
}
function my_meta_box_details () {
global $post;
$post_ID = $post->ID; // global used by get_upload_iframe_src
printf( "<iframe frameborder='0' src=' %s ' style='width: 100%%; height: 400px;'> </iframe>", get_upload_iframe_src('media') );
}
Once you add the editor, when you click 'Insert into post' you can see the inserted link in the editor. Which is presumably what you need.
There is a problem with disappearing metabox when you do upload the image.
In my opinion, you don't really need the extra uploader in a metabox. You have 'Add Media' Button above the editor - you can add images, videos or galleries in your CPT that way.
EDIT
You could ditch the media uploader and just call the default wp.media like this:
function my_meta_box_details () {
global $post;
// Here we get the current images ids of the gallery
$custom = get_post_custom($post->ID);
$my_gallery = (isset($custom["my_gallery"][0])) ? $custom["my_gallery"][0] : '';
// We display the gallery
?>
<style>
.gallery-item{
width:150px;
display: inline-block;
margin-right: 10px;
}
.gallery-item img{
width: 150px;
}
</style>
<div class="gallery_images">
<?php
$img_array = (isset($my_gallery) && $my_gallery != '') ? explode(',', $my_gallery) : '';
if ($img_array != '') {
foreach ($img_array as $img) {
echo '<div class="gallery-item">'.wp_get_attachment_image($img).'</div>';
}
}
?>
</div>
<p class="separator">
<input id="my_gallery_input" type="hidden" name="my_gallery" value="<?php echo $my_gallery; ?>" data-urls=""/>
<input id="manage_gallery" title="Manage gallery" type="button" value="Manage gallery" />
<input id="empty_gallery" title="Empty gallery" type="button" value="Empty gallery" />
</p>
<script>
jQuery(document).ready(function($) {
$(document).on('click', '#manage_gallery', upload_gallery_button);
function upload_gallery_button(e) {
e.preventDefault();
var $input_field = $('#my_gallery_input');
var ids = $input_field.val();
var gallerysc = '[gallery ids="' + ids + '"]';
wp.media.gallery.edit(gallerysc).on('update', function(g) {
var id_array = [];
var url_array = [];
$.each(g.models, function(id, img){
url_array.push(img.attributes.url);
id_array.push(img.id);
});
var ids = id_array.join(",");
ids = ids.replace(/,\s*$/, "");
var urls = url_array.join(",");
urls = urls.replace(/,\s*$/, "");
$input_field.val(ids);
var html = '';
for(var i = 0 ; i < url_array.length; i++){
html += '<div class="gallery-item"><img src="'+url_array[i]+'"></div>';
}
$('.gallery_images').html('').append(html);
});
}
$(document).on('click', '#empty_gallery', empty_gallery_button);
function empty_gallery_button(e){
e.preventDefault();
var $input_field = $('#my_gallery_input');
$input_field.val('');
$('.gallery_images').html('');
}
});
</script>
<?php
}
function my_metabox_save(){
global $post;
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return;
} elseif(is_object($post)){
$my_gallery = (isset($_POST['my_gallery'])) ? $_POST['my_gallery'] : '';
update_post_meta($post->ID, 'my_gallery', $my_gallery);
}
}
add_action('save_post', 'my_metabox_save');
And remove the editor from your supports argument. Should be working fine.

Resources