Wordpress: How to save values from repeater field? - wordpress

I am using this repeater plugin with a custom wordpress template https://github.com/DubFriend
/jquery.repeater
<div class="repeater">
<div data-repeater-list="category-group">
<div data-repeater-item>
<input type="hidden" name="id" id="cat-id"/>
<input type="text" name="cat-title" />
<input type="text" name="cat-slug" />
<input data-repeater-delete type="button" value="Delete"/>
</div>
</div>
<input data-repeater-create type="button" value="Add"/>
</div>
but values not saving in database
In save post function i have
add_shortcode('album','ty_front_end_form');
function ty_save_post_data() {
if ( empty($_POST) || !wp_verify_nonce($_POST['name_of_nonce_field'],'name_of_my_action') ) {
print 'Sorry, your nonce did not verify.';
exit;
} else {
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter a title';
exit;
}
$release= $_POST['custom_release'];
$artist = $_POST['custom_arname'];
$lang = $_POST['custom_lang'];
$id = $_POST['id'];
$catt = $_POST['cat-title'];
$cats = $_POST['cat-slug'];
$post = array(
'post_title' => wp_strip_all_tags( $title ),
'post_status' => 'publish',
'post_type' => 'album',
'meta_input' => array(
'custom_release' => $release,
'custom_arname' => $artist,
'custom_lang' => $lang,
'id' => $id,
'cat-title' => $catt,
'cat-slug' => $cats
)
);
$post_id = wp_insert_post($post);
$location = home_url();
echo "<meta http-equiv='refresh' content='0;url=$location' />";
exit;
} // end IF
}
and this is a shortcode for frontend user posting which is showing on a template page

Related

Create the custom payment gateway intregation in woocommerce

I am creating a custom gateway plugin for woocommerce for which I need the following workflow:
When customers click on the PLACE ORDER button on the checkout page
they need to be directed to the bank's hosted payment page to enter the card details and make the
payment. Once the payment is made, the bank sends the success/fail
response, and then only the order status is updated to
complete/canceled.
Also, the bank needs some information like merchant ID and other fields to process the payment.
I have created the plugin which adds hidden fields in the checkout page with necessary data that needs to be sent to the bank's payment page but I am having difficulties passing the data to the hosted payment page. Below is my full code
<?php
/*
** Check if Woocommerce is active
**
*/
if ( ! in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) return;
// create custom plugin settings menu
add_action('admin_menu', 'create_custom_menu');
function create_custom_menu() {
//create new top-level menu
add_menu_page('Plugin page Settings', 'Plugin Settings', 'administrator', __FILE__, 'plugin_settings_page' , plugins_url('/images/icon.png', __FILE__) );
//call register settings function
add_action( 'admin_init', 'register_plugin_settings' );
}
function register_plugin_settings() {
//register our settings
register_setting( 'plugin-settings-group', 'shop_id' );
register_setting( 'plugin-settings-group', 'shared_secret' );
register_setting( 'plugin-settings-group', 'currency_code' );
}
function plugin_settings_page() {
?>
<div class="wrap">
<form method="post" action="options.php">
<?php settings_fields( 'plugin-settings-group' ); ?>
<?php do_settings_sections( 'plugin-settings-group' ); ?>
<table class="form-table">
<tr valign="top">
<th scope="row">Shop ID</th>
<td><input type="text" name="shop_id" value="<?php echo esc_attr( get_option('shop_id') ); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Shared Secret</th>
<td><input type="text" name="shared_secret" value="<?php echo esc_attr( get_option('shared_secret') ); ?>" /></td>
</tr>
<tr valign="top">
<th scope="row">Currency Code</th>
<td><input type="text" name="currency_code" value="<?php echo esc_attr( get_option('currency_code') ); ?>" disabled/><br></td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php }
add_action( 'woocommerce_after_order_notes', 'add_custom_checkout_hidden_field' );
function add_custom_checkout_hidden_field( $checkout ) {
$shop_id = esc_attr( get_option('shop_id') );
$sharedSecret = esc_attr( get_option('shared_secret') );
$currency = "826";
// Output the hidden field
echo '<input type="hidden" name="shop_id" value="'.$shop_id.'" />
<input type="hidden" name="shop_id" value="'.$sharedSecret.'" />
<input type="hidden" name="shop_id" value="'.$currency.'" />
';
}
add_filter( 'woocommerce_payment_gateways', 'add_custom_gateway_class' );
function add_custom_gateway_class( $gateways ) {
$gateways[] = 'Custom_Gateway';
return $gateways;
}
add_action( 'plugins_loaded', 'plugin_init_gateway_class' );
function plugin_init_gateway_class() {
class Custom_Gateway extends WC_Payment_Gateway {
/**
* Class constructor
*/
public function __construct() {
$this->id = 'custom_gateway_id'; // payment gateway plugin ID
$this->icon = ''; // URL of the icon that will be displayed on checkout page near your gateway name
$this->has_fields = true; // in case you need a custom credit card form
$this->method_title = 'Custom Gateway';
$this->method_description = 'Description of Custom payment gateway'; // will be displayed on the options page
// Method with all the options fields
$this->init_form_fields();
// Load the settings.
$this->init_settings();
$this->title = $this->get_option( 'title' );
$this->description = $this->get_option( 'description' );
$this->enabled = $this->get_option( 'enabled' );
$this->shop_id = $this->get_option( 'shop_id' );
$this->test_mode = $this->get_option( 'test_mode' );
// This action hook saves the settings
add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
}
public function getDateTime(){
date_default_timezone_set('Europe/London');
$dateTime = date("Y:m:d-H:i:s");
global $dateTime;
return $dateTime;
}
public function createHash($chargetotal, $currency){
$storeId = $this->get_option( 'shop_id' );
$sharedSecret = $this->get_option( 'shared_secret' );
$stringToHash = $storeId.getDateTime().$chargetotal.$currency.$sharedSecret;
$ascii = bin2hex($stringToHash);
return hash("sha256", $ascii);
}
public function init_form_fields(){
$this->form_fields = array(
'enabled' => array(
'title' => 'Enable/Disable',
'label' => 'Enable Custom Gateway',
'type' => 'checkbox',
'description' => '',
'default' => 'no'
),
'title' => array(
'title' => 'Title',
'type' => 'text',
'description' => 'This controls the title which the user sees during checkout.',
'default' => 'Debit/Credit Card',
'desc_tip' => true,
),
'description' => array(
'title' => 'Description',
'type' => 'textarea',
'description' => 'This controls the description which the user sees during checkout.',
'default' => 'Pay with your debit/credit card.',
),
'test_mode' => array(
'title' => 'Test Mode',
'type' => 'checkbox',
'description' => 'Check this option to enable the test mode.',
'default' => 'yes',
)
);
}
public function process_payment( $order_id ) {
global $woocommerce;
$order = new WC_Order( $order_id );
$environment = $this->get_option( 'test_mode' );
if ($environment === 'yes') {
// TEST MODE
$redirect_url = 'https://mytesturl.com';
} else{
// PRODUCTION MODE
$redirect_url = 'https://myproductionurl.com';
}
return array(
'result' => 'success',
'redirect' => $redirect_url
);
}
}
}
Can someone assist me please, how can I pass the required data to the hosted payment page and update the order status once the response is received from the bank?

filter by custom field WordPress

I want to search posts by custom field type.
I have custom field "country "with a custom post type umrahpackage now I want if a visitor search for a country "abc" its should show all posts with abc country.
here is my code but not working.
`
add_shortcode('user_search','My_User_search');
function My_User_search($atts = null)
{
$out = user_search_form();
$args = array(
'post_type' => 'umrahpackage',
'meta_query' => array(
array(
'key' => 'country',
'value' => 'pakistan',
'compare' => 'LIKE',
))
);
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ):
while( $the_query->have_posts() ) : $the_query->the_post();
$out .= '<li>' . get_the_title() . '</li>';
endwhile;
endif;
return $out;
}
//function to display user search form
function user_search_form(){
$metavalue = $metakey = '';
if (isset($_GET['search_by'])){
$metakey = $_GET['search_by'];
}
if (isset($_GET['s_value'])){
$metavalue = $_GET['s_value'];
}
$re = '<div class="user_search"><form action="" name="user_s" method="get">
<label for="search_by">Search by:</label>
<select id="search_by" name="search_by">';
if ($metakey != ''){
$re.= '"';
$re.= ($metakey == "country") ;
}else{
$re .= '
<option value="country">Comapny Name</option>';
}
$re .= '
</select>
<label>Company Name</label>
<input id="s_value" name="s_value" type="text" value="'.$metavalue.'"/>
<input type="hidden" id="user_search" name="post_type" value="umrahpackage" />
<input id="submit" type="submit" value="Search" />
</form></div>';
return $re;
}`
I solved it I share it if its help some one else
add_shortcode('user_search','My_User_search');
function My_User_search($atts = null){
$out = user_search_form();
$args = array('post_type' => 'umrahpackage','order' => 'asc',
'meta_query' => array(
array(
'key' => 'country',
'value' => $_GET['s_value'],
'compare' => 'Like',
)
)
);
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ):
while( $the_query->have_posts() ) : $the_query->the_post();
if($_GET['s_value']==''){
//before search hide the posts
}
else {
$out .= '<li>' . get_the_title() . '</li>';
}
endwhile;
endif;
return $out;
}
function user_search_form(){
$re = '<div class="user_search"><form action="" name="user_s" method="get">
<label for="search_by">Search by:</label>
<div id="search_by" name="search_by">';
$re .= '
<label>Company Name</label>
<input id="s_value" name="s_value" type="text" value="'.$metavalue.'"/>
<input name="user_search" id="user_search" type="hidden" value="umrahpackage"/>
<input id="submit" type="submit" value="Search" />
</form></div>';
return $re;
}
?>

How to upload Web-record Base64 Wave Audio file in WordPress Post (front-end form)

I created a WordPress post form that works well
And I want to add a field:
Browser recording audio file
Based on base64 - (blob file)
And upload when posting.
My javascript code is :
https://subinsb.com/html5-record-mic-voice/
This is my code example:
<?php
if ( isset( $_POST['submitted'] ) && isset( $_POST['post_nonce_field'] ) && wp_verify_nonce( $_POST['post_nonce_field'], 'post_nonce' ) ) {
if ( trim( $_POST['postTitle'] ) === '' ) {
$postTitleError = 'Please enter a title.';
$hasError = true;
}
$post_information = array(
'post_title' => wp_strip_all_tags( $_POST['postTitle'] ),
'post_content' => $_POST['postContent'],
'episode' => $_POST['postEpisode'],
'post_type' => 'post',
'post_status' => 'draft'
);
$post_id = wp_insert_post( $post_information );
add_post_meta($post_id, 'episode', $_POST['postEpisode'], true);
/* upload file here */
$file_name = $_FILES['fileToUpload']['name'];
$file_temp = $_FILES['fileToUpload']['tmp_name'];
$upload_dir = wp_upload_dir();
$image_data = file_get_contents( $file_temp );
$filename = basename( $file_name );
$filetype = wp_check_filetype($file_name);
$filename = time().'.'.$filetype['ext'];
if ( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
}
else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents( $file, $image_data );
$wp_filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file,$post_id );
wp_update_attachment_metadata( $attach_id, $attach_data,$post_id );
echo $attach_id;
}
?>
<?php if ( $postTitleError != '' ) { ?>
<span class="error"><?php echo $postTitleError; ?></span>
<div class="clearfix"></div>
<?php } ?>
<?php
if ( $post_id ) {
wp_redirect( home_url() );
exit;
}
?>
<form action="" id="primaryPostForm" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="postTitle"><?php _e('Post Title:', 'framework') ?></label>
<input type="text" name="postTitle" id="postTitle" class="required" value="" />
</fieldset>
<fieldset>
<label for="postContent"><?php _e('Post Content:', 'framework') ?></label>
<textarea name="postContent" id="postContent" rows="8" cols="30" class="required"></textarea>
</fieldset>
<fieldset>
<label for="postEpisode"></label>
<textarea name="postEpisode" id="postEpisode" rows="8" cols="30" class="required"></textarea>
</fieldset>
<?php
/*----------------- recorder filed here -----------------*/
?>
<audio controls id="audio"></audio>
<div>
<a class="button recordButton" id="record">Record</a>
<a class="button recordButton" id="recordFor5">Record For 5 Seconds</a>
<a class="button disabled one" id="pause">Pause</a>
<a class="button disabled one" id="stop">Reset</a>
</div><br/>
<div>
<input class="button" type="checkbox" id="live"/>
<label for="live">Live Output</label>
</div>
<div data-type="wav">
<p>WAV Controls:</p>
<a class="button disabled one" id="play">Play</a>
<a class="button disabled one" id="download">Download</a>
<a class="button disabled one" id="base64">Base64 URL</a>
<a class="button disabled one" id="save">Upload to Server</a>
</div>
<canvas id="level" height="200" width="500"></canvas>
<fieldset>
<?php wp_nonce_field( 'post_nonce', 'post_nonce_field' ); ?>
<input type="hidden" name="submitted" id="submitted" value="true" />
<button type="submit"><?php _e('Add Post', 'framework') ?></button>
</fieldset>
</form>
javascript file:
function restore(){
$("#record, #live").removeClass("disabled");
$(".one").addClass("disabled");
Fr.voice.stop();
}
$(document).ready(function(){
$(document).on("click", "#record:not(.disabled)", function(){
elem = $(this);
Fr.voice.record($("#live").is(":checked"), function(){
elem.addClass("disabled");
$("#live").addClass("disabled");
$(".one").removeClass("disabled");
});
});
$(document).on("click", "#stop:not(.disabled)", function(){
restore();
});
$(document).on("click", "#play:not(.disabled)", function(){
Fr.voice.export(function(url){
$("#audio").attr("src", url);
$("#audio")[0].play();
}, "URL");
restore();
});
$(document).on("click", "#download:not(.disabled)", function(){
Fr.voice.export(function(url){
$("<a href='"+url+"' download='MyRecording.wav'></a>")[0].click();
}, "URL");
restore();
});
$(document).on("click", "#base64:not(.disabled)", function(){
Fr.voice.export(function(url){
console.log("Here is the base64 URL : " + url);
alert("Check the web console for the URL");
$("<a href='"+ url +"' target='_blank'></a>")[0].click();
}, "base64");
restore();
});
$(document).on("click", "#mp3:not(.disabled)", function(){
alert("The conversion to MP3 will take some time (even 10 minutes), so please wait....");
Fr.voice.export(function(url){
console.log("Here is the MP3 URL : " + url);
alert("Check the web console for the URL");
$("<a href='"+ url +"' target='_blank'></a>")[0].click();
}, "mp3");
restore();
});
});
I have searched several websites and unfortunately found no right solution to this problem.
I want to upload this file along with the post.And display in a custom field in the backend
Can anyone help me?

Custom WordPress search with multiple text fields

I need to create a custom WordPress search form, with multiple text input fields. Each text field should search its corresponding meta key. Frontend would look like this:
Search form:
<form role="search" action="/" method="get" id="searchform">
<input type="text" name="s" placeholder="Name"/>
<input type="text" name="hometown" placeholder="Hometown"/>
<input type="text" name="branch" placeholder="Branch of Service"/>
<input type="text" name="birth" placeholder="Birth Year"/>
<input type="text" name="casualty" placeholder="Casualty Year"/>
<input type="text" name="location" placeholder="Casualty Location">
<input type="hidden" name="post_type" value="veterans" />
<input type="submit" alt="Search" value="Search" />
</form>
The "Name" field should search the post title only. The rest of the input fields would search a specific custom meta key. It would use an "AND" relationship when multiple fields are used.
Is this possible? Here is what I have tried, but it doesn't search if the name ("s") is empty, and it doesn't seem to be affected at all by what I enter into the custom fields for Hometown or Branch.
// register query vars
function sm_register_query_vars( $vars ) {
$vars[] = 'hometown';
$vars[] = 'branch';
return $vars;
}
add_filter( 'query_vars', 'sm_register_query_vars' );
// pre get posts
function sm_pre_get_posts( $query ) {
if ( is_admin() || ! $query->is_main_query() ){
return;
}
if ( !is_post_type_archive( 'veterans' ) ){
return;
}
$meta_query = array();
// add meta_query elements
if( !empty( get_query_var( 'hometown' ) ) ){
$meta_query[] = array( 'key' => 'hometown', 'value' => get_query_var( 'hometown' ), 'compare' => 'LIKE' );
}
if( !empty( get_query_var( 'branch' ) ) ){
$meta_query[] = array( 'key' => 'branch', 'value' => get_query_var( 'branch' ), 'compare' => 'LIKE' );
}
if( count( $meta_query ) > 1 ){
$meta_query['relation'] = 'AND';
}
if( count( $meta_query ) > 0 ){
$query->set( 'meta_query', $meta_query );
}
}
add_action( 'pre_get_posts', 'sm_pre_get_posts', 1 );
// the search form (display via shortcode)
function sm_search_form( $args ){
$output = '<form id="smform" action="' . esc_url( home_url() ) . '" method="GET" role="search">';
$output .= '<div class="smtextfield"><input type="text" name="s" placeholder="Name" value="' . get_search_query() . '" /></div>';
$output .= '<div class="smtextfield"><input type="text" name="hometown" placeholder="Hometown" value="' . get_search_query() . '" /></div>';
$output .= '<div class="smtextfield"><input type="text" name="branch" placeholder="Branch" value="' . get_search_query() . '" /></div>';
$output .= '<input type="hidden" name="post_type" value="veterans" />';
$output .= '<p><input type="submit" value="Search" class="button" /></p></form>';
return $output;
}
The above query looks like this when attempting to search:
site.com/?s=john+doe&branch=army&hometown=new+york&post_type=veterans
After checking if there are any terms in your search by something like
if($_GET['myfield'])...
try storing each type of your search in a var and then build a custom query with all the items that are in your search. ie :
<?php
$title=$_GET['name']; // Get the name
$params=[]; // Create an array with all the parameters you've got except the name
function populate_array($term) // Create a function to populate your array
{
if ($_GET[$term]) {
$params[$term] = $_GET[$term];
}
}
populate_array('hometown');
populate_array('branch');
//(...)
$args=array( // Initialize your query
'post_type' => 'my_post_type', // Just set your post type if needed
);
if($title){ // If there is a title add it to the query
$args['title']=$title;
}
if(count($params)>0){. // If there are any params
$meta=array('relation'=>'AND'); // Because you asked for it
foreach($params as $param => $value){
$meta[]=array( // Adding each meta tou your query
'key' => $param, // considering you name your meta as your parameter
'value' => $value,
'compare' => '='
);
}
$args['meta_query']=$meta; // Adding your meta to your main query
}
$query = new WP_Query( $args ); // And now you can request your query with all your parameters
I have not tested this but it should work... Maybe some improvements are needed. Test it and come back to me :)

Array of checkboxes not saving in WordPress widget

This is my code for the widget:
function form( $instance ) {
$instance = wp_parse_args( (array)$instance, array(
'checkboxes' => array(
'Monday' => array('name' => 'Monday', 'value' => 'Monday', 'checked' => 1),
'Tuesday' => array('name' => 'Tuesday', 'value' => 'Tuesday', 'checked' => ''),
'Wednesday' => array('name' => 'Wednesday', 'value' => 'Wednesday', 'checked' => ''),
'Thursday' => array('name' => 'Thursday', 'value' => 'Thursday', 'checked' => ''),
'Friday' => array('name' => 'Friday', 'value' => 'Friday', 'checked' => ''),
'Saturday' => array('name' => 'Saturday', 'value' => 'Saturday', 'checked' => ''),
'Sunday' => array('name' => 'Sunday', 'value' => 'Sunday', 'checked' => '')
),
'title' => 'Workdays'
));
include( plugin_dir_path(__FILE__) . '/views/admin.php' );
}
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['checkboxes'] = strip_tags($new_instance['checkboxes']);
return $instance;
}
This is the code for the view:
<div class='ws-business-info'>
<div class='form-group'>
<?php foreach($instance['checkboxes'] as $day ) : ?>
<div class='checkbox'>
<label>
<input type="checkbox"
name="<?php echo $day['name']; ?>"
class="form-control"
id="<?php echo $this->get_field_id($day['name']); ?>"
value="<?php echo $day['value']; ?>"
<?php checked('1', $day['checked']); ?>/>
<?php echo $day['name']; ?>
</label>
</div>
<?php endforeach; ?>
</div>
The widget displays the checkboxes as expected but the state will not save. Dumping the $old_instance variable in the update function gives a null value.
In the view file you defined input's id corectly, but you did not the same with name attribute.
Define the name attribute like this:
<input type="checkbox"
name="<?php echo $this->get_field_name( 'checkboxes' ), '[', esc_attr( $day['name'] ), ']'; ?>"
class="form-control"
id="<?php echo $this->get_field_id($day['name']); ?>"
value="<?php echo $day['value']; ?>"
<?php checked('1', $day['checked']); ?>/>
<?php echo $day['name']; ?>
public function widget( $args, $instance ) {
// outputs the content of the widget
}
This function has to be added along with the default constructor. Else the widget will not work.
Not exactly what you are looking for but this is how I saved a checkbox in metabox, you may get some hint from this...
Code used to display html
function html_rtsocial_metabox()
{
global $post;
$custom = get_post_custom($post->ID);
$suppress = $custom['_suppress_rtsocial'][0];
$checked = ($suppress=='yes')?'checked':'';
$value = ($suppress=='yes')?'yes':'no';
$html = '<br><input type="checkbox" name="_suppress_rtsocial" value="'.$value.'" '.$checked.' id="_suppress_rtsocial" /> Hide Social Icons ???';
$html .= '<br/><br/>';
echo $html;
}
While saving
update_post_meta($post_id,'_suppress_rtsocial',$_POST['_suppress_rtsocial']);
Added js for admin interface
function checkbox_helper(){
var ele =jQuery('#_suppress_rtsocial'),value;
ele.click(function(){
value = ele.is(':checked')?'yes':'no';
ele.val(value);
}
);
}

Resources