I have created dynamic add / remove file field to insert image in database. But somehow it is not working properly. Following is my code...
$member_image_names = array_map( 'sanitize_file_name', $_FILES['member_image']['name'] );
foreach ( $member_image_names as $member_image_name ) {
if ( empty( $member_image_name ) ) {
global $wpdb;
$project_id = $_SESSION['project_id'];
$project_member_details = $wpdb->get_var( $wpdb->prepare( "SELECT project_members FROM wpxa_orocox_project_members WHERE project_id = %d", $project_id ) );
$project_member_detail = json_decode( $project_member_details, true );
$member_image_newname = $project_member_detail['member_image'];
} else {
$member_image_ext = strtolower( end( explode( '.', $member_image_name ) ) );
$member_image_newname[] = get_current_user_id() . $_SESSION['project_id'] . "_" . time() . "_" . mt_rand() . "." . $member_image_ext;
}
$member_details->member_image = $member_image_newname;
$member_details_encode = wp_json_encode( $member_details );
global $wpdb;
$members_result_update = $wpdb->update( 'wpxa_project_members',
array( 'project_members' => $member_details_encode ),
array( 'project_id' => $_SESSION['project_id'] ),
array( '%s' ),
array( '%d' )
);
if ( ! empty( $members_result_update ) ) {
$member_details_decode = json_decode($member_details_encode, true);
$count_member_decode = count( $member_details_decode['member_image'] );
for ( $i = 0; $i < $count_member_decode; $i++ ) {
$m_image_name = $member_details_decode['member_image'][$i];
$profile_image_folder = "profile-images/";
$profile_image_path = trim( $profile_image_folder . basename( $m_image_name ) );
$profile_image_temp = $_FILES['member_image']['tmp_name'][$i];
$profile_image_ext = strtolower( end( explode( '.', $m_image_name ) ) );
if ( $profile_image_ext == "jpg" || $profile_image_ext == "png" || $profile_image_ext == "jpeg" || $profile_image_ext == "gif" ) {
move_uploaded_file( $profile_image_temp, $profile_image_path );
}
}
}
}
Every thing works well but when I select a new image in first field and submit the value to the database, it removes all other images of other fields from database...
And if I select image for other fields and submit the value to database it then creates new field with that value...
In simple terms, When I want to update any particular file field in the dynamic add / remove file field then that particular field should only be get updated and other fields should remain intact.
Pl Help...
I had this problem and i did it :(Example)
if ( empty( $options['index1_cardimg'] ) ) {$options['index1_cardimg'] = get_myoption_value('index1_cardimg');}
without this check (if (empty){}) all other fields will be reset .
just you need to fill them by last data (if they dont send) .
with a code like this:
if ( empty( $members_result_update ) ) {
// fill Other options with last value
}
Related
This is my code using PHPExcel and NinjaForms. Basically the code does go inside if( isset($sub[$field_key]) ){ so all data is OK. I have also echoed it but somehow the rows are empty.
public function export_file( $form_id ) {
// set xls always on
$use_xls = true;
// set save dir
$upload_dir = wp_upload_dir();
$tmp_file = $upload_dir['basedir'] . '/test/' . $form_id . '/form-submissions-'. $form_id .'.xls';;
$sub_results = $this->get_submissions( $form_id );
$num_submissions = $this->count_submissions($form_id );
$fields_meta = Ninja_Forms()->form($form_id)->get_fields();
$field_names=array();
$header_row=array();
$header_row['id'] = __('ID','ninja-forms-spreadsheet');
$header_row['date_submitted'] = __('Submission date','ninja-forms-spreadsheet');
foreach($fields_meta as $field_id => $field){
$field_settings = $field->get_settings();
// skip save fields
if( $field_settings['type'] == 'save' || $field_settings['type'] == 'submit' ) {
unset( $fields_meta[$field_id] );
continue;
}
$field_names[$field_id] = sanitize_title( $field_settings['label'].'-'.$field_id );
$field_types[$field_id] = $field_settings['type'];
$header_row[$field_id] = $field_settings['label'];
}
//die();
require_once( plugin_dir_path( __DIR__ ).'/ninja-forms-excel-export/includes/PHPExcel.php');
$objPHPExcel = new PHPExcel();
$row_number = 1;
// this should be the same wordpress uses and therefore be the saver choice
PHPExcel_Shared_File::setUseUploadTempDirectory( true );
// Table Headline
$col_index = 0;
foreach ($header_row as $headline) {
$col = PHPExcel_Cell::stringFromColumnIndex( $col_index );
$objPHPExcel->getActiveSheet()->getCell($col.$row_number)->setValue( $headline );
$objPHPExcel->getActiveSheet()->getStyle($col.$row_number)->getFont()->setBold(true);
$col_index++;
}
$objPHPExcel->getActiveSheet()->freezePane( "A2" );
$row_number++;
/*
* Loop over each sub
*/
foreach($sub_results as $sub){
$col = 'A';
$objPHPExcel->getActiveSheet()->getCell($col++.$row_number)->setValueExplicit( $sub['_seq_num'], PHPExcel_Cell_DataType::TYPE_NUMERIC );
$objPHPExcel->getActiveSheet()->getCell($col++.$row_number)->setValueExplicit( $sub['date_submitted'] );
$col_index = 0;
foreach ($fields_meta as $field_id => $field) {
$field_key = '_field_'.$field_id;
if( isset($sub[$field_key]) ){
$field_value = $sub[$field_key];
$col = PHPExcel_Cell::stringFromColumnIndex( 2+$col_index );
$field_value = maybe_unserialize( $field_value );
echo $field_types[$field_id] . ' ';
if( in_array($field_types[$field_id], array( 'shipping', 'total', 'number' ) ) ){ // float values
$objPHPExcel->getActiveSheet()->getCell($col.$row_number) ->setValueExplicit( $field_value, PHPExcel_Cell_DataType::TYPE_NUMERIC );
$objPHPExcel->getActiveSheet()->getStyle($col.$row_number)
->getNumberFormat()
->setFormatCode('#,##');
}elseif( in_array($field_types[$field_id], array( 'starrating', 'quantity' ) ) ){ // integer values
$objPHPExcel->getActiveSheet()->getCell($col.$row_number) ->setValueExplicit( $field_value, PHPExcel_Cell_DataType::TYPE_NUMERIC );
$objPHPExcel->getActiveSheet()->getStyle($col.$row_number)
->getNumberFormat()
->setFormatCode('#');
}elseif( in_array($field_types[$field_id], array( 'checkbox' ) ) || strpos($field_types[$field_id], '-optin') ){
$objPHPExcel->getActiveSheet()->getCell($col.$row_number)->setValueExplicit( $field_value, PHPExcel_Cell_DataType::TYPE_STRING );
}elseif( in_array($field_types[$field_id], array( 'listcheckbox' ) ) ){
$field_output = $field_value;
if( is_array($field_value) ){
$field_output = '';
foreach ($field_value as $key => $value) {
if( $field_output == '' )
$field_output = $value;
else
$field_output .= ', ' . $value;
}
}
$objPHPExcel->getActiveSheet()->getCell($col.$row_number)->setValueExplicit( htmlspecialchars_decode ( $field_output,ENT_QUOTES ), PHPExcel_Cell_DataType::TYPE_STRING );
}elseif( $field_types[$field_id] == 'file_upload' ){
if( is_array($field_value)){
$field_value = implode("\n", $field_value);
}
$objPHPExcel->getActiveSheet()->getCell($col.$row_number)->setValueExplicit( htmlspecialchars_decode ( $field_value,ENT_QUOTES ), PHPExcel_Cell_DataType::TYPE_STRING );
$objPHPExcel->getActiveSheet()->getStyle($col.$row_number)
->getAlignment()
->setWrapText(true);
}elseif( $field_types[$field_id] == 'textarea' ){
$objPHPExcel->getActiveSheet()->getCell($col.$row_number)->setValueExplicit( htmlspecialchars_decode ( $field_value,ENT_QUOTES ), PHPExcel_Cell_DataType::TYPE_STRING );
$objPHPExcel->getActiveSheet()->getStyle($col.$row_number)
->getAlignment()
->setWrapText(true);
}else{
if( is_array($field_value) ){
$field_value = implode('; ', $field_value);
}
$objPHPExcel->getActiveSheet()->getCell($col.$row_number)->setValueExplicit( htmlspecialchars_decode ( $field_value,ENT_QUOTES ), PHPExcel_Cell_DataType::TYPE_STRING );
}
}
$col_index++;
}
$row_number++;
}
$objWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
ob_end_clean();
$objWriter->save($tmp_file);
}
The excel modified time is updated correctly but all rows are empty except the first header row in bold. I am not sure what is the issue.
Any help is appreciated.
Okay, i have one Wordpress website, and this is one shortcode. This basically updates the database and refresh the current page. But I want another version this shortcode, which does not reload the page.
add_action("init","start_ob_start_cb");
function start_ob_start_cb()
{
ob_start();
}
add_shortcode( 'mycred_take', 'mycred_pro_render_take_shortcode' );
function mycred_pro_render_take_shortcode( $atts, $label = 'Give Away' ) {
extract( shortcode_atts( array(
'user_id' => '',
'confirm' => '',
'amount' => '',
'unique' => 0,
'ref' => 'mycred_take',
'entry' => '%plural% lose',
'ctype' => 'mycred_default'
), $atts ) );
if ( ! is_user_logged_in() || ! function_exists( 'mycred' ) ) return '';
if ( $user_id == '' )
$user_id = get_current_user_id();
// Load essentials
$user_id = absint( $user_id );
$mycred = mycred( $ctype );
// User is excluded = has no balance
if ( $mycred->exclude_user( $user_id ) ) return '';
// Unique check
if ( $unique == 1 && $mycred->has_entry( $ref, 0, $user_id, '', $ctype ) ) return '';
$balance = $mycred->get_users_balance( $user_id, $ctype );
$output = '';
// If button was pushed
if ( isset( $_POST['mycred-take-points-token'] ) && wp_verify_nonce( $_POST['mycred-take-points-token'], 'mycred-deduct-points' . $ref . $ctype ) ) {
// Deduct
$mycred->add_creds(
$ref,
$user_id,
0 - $amount,
$entry
);
// Update balance
$balance = $balance - $amount;
wp_redirect(get_permalink()); die();
}
// Too low balance
if ( $balance < $amount ) return '';
return $output . '<form action="" method="post" id="mycred-take-shortcode' . $ref . $ctype . '"><input type="hidden" name="mycred-take-points-token" value="' . wp_create_nonce( 'mycred-deduct-points' . $ref . $ctype ) . '" /><input type="submit" class="button" value="' . $label . '" /></form>';
}
I'd like to make sure that when click on the button, should not reload the page, only if manually reload. I tried it simple POST, but no way i can come up with a solution.
Use AJAX approach that will trigger when the submit button is clicked. Try to google on how to do this and comeback to us if you still need an assistance.
Hi i've been trying to generate the following XML with PHP.
I've managed to generate it all except for the location section as it seems to treat it as another root and error out. Does anyone know the correct way to produce this?
<?xml version="1.0" encoding="UTF-8"?>
<classifieds xmlns="http://www.bdjjobs.com/ClassifiedJobFromRecruiterFeed">
<job>
<reference_id>20161114-72</reference_id>
<recruiter>Smiles R Us</recruiter>
<job_title>Denture Specialist</job_title>
<short_description><![CDATA[An exciting position in a dynamic dental practice]]></short_description>
<description><![CDATA[<p>Full description of post</p>]]></description>
<location>
<city>city</city>
<state>county</state>
<country>country</country>
</location>
<salary_description><![CDATA[Full Package]]></salary_description>
<organisations>Independent Dental Practice</organisations>
<job_type>Specialist Appointments</job_type>
<salary_band>£100,000 or more</salary_band>
<contract_type>Associate Permanent</contract_type>
<hours>Full time</hours>
<practice_type>Mixed (NHS/Private)</practice_type>
<start_date>2016-09-01</start_date>
<expiry_date>2016-10-30</expiry_date>
<application_email>apply_here#email.com</application_email>
</job>
</classifieds>
Any assistance would be greatly appreciated, thanks :)
Here is the code:
// Start Job Element
$job_element = $xml_document->createElement("job");
// Job ID
$rootreferencenumber = $xml_document->createElement("reference_id");
$rootreferencenumber->appendChild($xml_document->createCDATASection( get_the_ID() ));
$job_element->appendChild($rootreferencenumber);
// Recruiter
$recruiter = $xml_document->createElement("recruiter");
$recruiter->appendChild($xml_document->createCDATASection( "MBR Dental Recruitment" ));
$job_element->appendChild($recruiter);
// Job title
$title = $xml_document->createElement("title");
$title->appendChild($xml_document->createCDATASection( get_the_title() ) );
$job_element->appendChild($title);
// Job Description
$description = $xml_document->createElement("description");
$description->appendChild($xml_document->createCDATASection( ( strip_tags( str_replace( "</p>", "\n\n", get_the_content() ) ) ) ) );
$job_element->appendChild($description);
// City
$city = $xml_document->createElement("city");
$get_city = explode( ',', get_post_meta( get_the_ID(), 'geolocation_city', true ) );
$city->appendChild($xml_document->createCDATASection( $get_city[0] ) );
$job_element->appendChild($city);
// Region from Taxonomy
$region = $xml_document->createElement("region");
$categories = wp_get_post_terms( get_the_ID(), 'job_listing_region', array( "fields" => "names" ) );
if ( $categories && ! is_wp_error( $categories ) ) {
$region->appendChild( $xml_document->createCDATASection( implode( ',', $categories ) ) );
} else {
$region->appendChild( $xml_document->createCDATASection( '' ) );
}
$job_element->appendChild($region);
// Create Company Name
$company_name = $xml_document->createElement("organisations");
$company_name->appendChild($xml_document->createCDATASection('xx'));
$job_element->appendChild($company_name);
// Create Phone Number
$phone_number = $xml_document->createElement("phone_number");
$phone_number->appendChild($xml_document->createCDATASection('0000'));
$job_element->appendChild($phone_number);
// Job direct URL
$url = $xml_document->createElement("application_url");
$url->appendChild($xml_document->createCDATASection(get_permalink( get_the_ID() )));
$job_element->appendChild($url);
// Category
$phone_number = $xml_document->createElement("job_type");
$phone_number->appendChild($xml_document->createCDATASection('Job'));
$job_element->appendChild($phone_number);
// Subcategory
$region = $xml_document->createElement("subcategory");
$categories = wp_get_post_terms( get_the_ID(), 'job_listing_category', array( "fields" => "names" ) );
if ( $categories && ! is_wp_error( $categories ) ) {
$region->appendChild( $xml_document->createCDATASection( implode( ',', $categories ) ) );
} else {
$region->appendChild( $xml_document->createCDATASection( '' ) );
}
$job_element->appendChild($region);
// Job date based on todays date
$date = $xml_document->createElement("start_date");
$date->appendChild($xml_document->createCDATASection(date(Ymd) ));
$job_element->appendChild($date);
// Job date expire from original post date
$expiry_date = $xml_document->createElement("expiry_date");
$wpDate = (date(Ymd) );
$wpDate = new DateTime($wpDate);
$wpDate->add(new DateInterval('P14D')); // P14D means a period of 14 days
$wpDate = $wpDate->format('Ymd');
$expiry_date->appendChild($xml_document->createCDATASection( $wpDate ));
$job_element->appendChild($expiry_date);
// Create Application Email Address
$app_email = $xml_document->createElement("application_email");
$app_email->appendChild($xml_document->createCDATASection('xx#xx.com'));
$job_element->appendChild($app_email);
// End Job Element
$root->appendChild($job_element);
Ok so i was approaching this completely wrong..
I needed to append the child elements (City + Region) to the new $location element. Not to the original $job_element
here is the correct code:
// Start Job Element
$job_element = $xml_document->createElement("job");
// Job ID
$rootreferencenumber = $xml_document->createElement("reference_id");
$rootreferencenumber->appendChild($xml_document->createCDATASection( get_the_ID() ));
$job_element->appendChild($rootreferencenumber);
// Recruiter
$recruiter = $xml_document->createElement("recruiter");
$recruiter->appendChild($xml_document->createCDATASection( "xx" ));
$job_element->appendChild($recruiter);
// Job title
$title = $xml_document->createElement("title");
$title->appendChild($xml_document->createCDATASection( get_the_title() ) );
$job_element->appendChild($title);
// Job Description
$description = $xml_document->createElement("description");
$description->appendChild($xml_document->createCDATASection( ( strip_tags( str_replace( "</p>", "\n\n", get_the_content() ) ) ) ) );
$job_element->appendChild($description);
//Create Location Element
$location = $xml_document->createElement("location");
$job_element->appendChild($location);
// City
$city = $xml_document->createElement("city");
$get_city = explode( ',', get_post_meta( get_the_ID(), 'geolocation_city', true ) );
$city->appendChild($xml_document->createCDATASection( $get_city[0] ) );
$location->appendChild($city);
// Region from Taxonomy
$region = $xml_document->createElement("region");
$categories = wp_get_post_terms( get_the_ID(), 'job_listing_region', array( "fields" => "names" ) );
if ( $categories && ! is_wp_error( $categories ) ) {
$region->appendChild( $xml_document->createCDATASection( implode( ',', $categories ) ) );
} else {
$region->appendChild( $xml_document->createCDATASection( '' ) );
}
$location->appendChild($region);
// Country Code
$country = $xml_document->createElement("country");
$country->appendChild($xml_document->createCDATASection('UK'));
$location->appendChild($country);
// Create Company Name
$company_name = $xml_document->createElement("organisations");
$company_name->appendChild($xml_document->createCDATASection('xx'));
$job_element->appendChild($company_name);
// Create Phone Number
$phone_number = $xml_document->createElement("phone_number");
$phone_number->appendChild($xml_document->createCDATASection('xx'));
$job_element->appendChild($phone_number);
// Job direct URL
$url = $xml_document->createElement("application_url");
$url->appendChild($xml_document->createCDATASection(get_permalink( get_the_ID() )));
$job_element->appendChild($url);
// Category
$job_type = $xml_document->createElement("job_type");
$job_type->appendChild($xml_document->createCDATASection('Job'));
$job_element->appendChild($job_type);
// Subcategory
$region = $xml_document->createElement("subcategory");
$categories = wp_get_post_terms( get_the_ID(), 'job_listing_category', array( "fields" => "names" ) );
if ( $categories && ! is_wp_error( $categories ) ) {
$region->appendChild( $xml_document->createCDATASection( implode( ',', $categories ) ) );
} else {
$region->appendChild( $xml_document->createCDATASection( '' ) );
}
$job_element->appendChild($region);
// Job date based on todays date
$date = $xml_document->createElement("start_date");
$date->appendChild($xml_document->createCDATASection(date(Ymd) ));
$job_element->appendChild($date);
// Job date expire from original post date
$expiry_date = $xml_document->createElement("expiry_date");
$wpDate = (date(Ymd) );
$wpDate = new DateTime($wpDate);
$wpDate->add(new DateInterval('P14D')); // P14D means a period of 14 days
$wpDate = $wpDate->format('Ymd');
$expiry_date->appendChild($xml_document->createCDATASection( $wpDate ));
$job_element->appendChild($expiry_date);
// Create Application Email Address
$app_email = $xml_document->createElement("application_email");
$app_email->appendChild($xml_document->createCDATASection('x#xx.net'));
$job_element->appendChild($app_email);
// End Job Element
$root->appendChild($job_element);
$old = get_post_meta($post_id, 'figure_sugsubject_repeatable_fields', true);
$new = array();
$figuresugsubjectpositions = $_POST['figuresugsubjectposition'];
$figuresugsubjectworkplaces = $_POST['figuresugsubjectworkplace'];
$figuresugsubjectlocations = $_POST['figuresugsubjectlocation'];
$figuresugsubjectfroms = $_POST['figuresugsubjectfrom'];
$figuresugsubjectstatuss = $_POST['figuresugsubjectstatus'];
$count = count( $figuresugsubjectpositions );
for ( $i = 0; $i < $count; $i++ ) {
if ( $figuresugsubjectpositions[$i] != '' ) :
$new[$i]['figuresugsubjectposition'] = stripslashes( strip_tags( $figuresugsubjectpositions[$i] ) );
$new[$i]['figuresugsubjectworkplace'] = $figuresugsubjectworkplaces[$i];
$new[$i]['figuresugsubjectlocation'] = $figuresugsubjectlocations[$i];
$new[$i]['figuresugsubjectfrom'] = $figuresugsubjectfroms[$i];
$new[$i]['figuresugsubjectstatus'] = $figuresugsubjectstatuss[$i];
endif;
}
if ( !empty( $new ) && $new != $old )
update_post_meta( $post_id, 'figure_sugsubject_repeatable_fields', $new );
elseif ( empty($new) && $old )
delete_post_meta( $post_id, 'figure_sugsubject_repeatable_fields', $old );
I have a frontend form for post submission. I want the new entries in the form not to replace the old ones, instead I want it to be added. To replace update_post_meta with add_post_meta will not solve the problem as users will not be able to edit their old inputs.
Thank you.
I seem to be having trouble with another piece of what seems to be super basic PHP, but it just won't work for me.
My client (real estate website) needs to be able to have properties with no price to be either “price upon request” OR “auction”. Currently, leaving the price field blank only allows for one.
I tried changing the following code:
$listing_price_labels = array(
‘sold’ => __( ‘Sold’, ‘wpsight’ ),
‘rented’ => __( ‘Rented’, ‘wpsight’ ),
‘request’ => __( ‘Price on request’, ‘wpsight’ ),
‘auction’ => __( ‘Auction’, ‘wpsight’ ), ***– Added this line***
);
And where this code is found…
if( is_admin() )
$listing_price .= ‘<br />’ . wpsight_get_price_value();
} elseif( empty( $listing_price ) ) {
// When no price available Price on request
$listing_price = ‘<span class=”listing-price-on-request”>’ . $listing_price_labels['request'] . ‘</span><!– .listing-price-on-request –>’;
} elseif( $listing_price = ‘auction’ ) {
// When price field contains ‘auction’ (case sensitive)
$listing_price = ‘<span class=”listing-price-on-request”>’ . $listing_price_labels['auction'] . ‘</span><!– .listing-price-on-request –>’;
}
function wpsight_get_price( $post_id = '' ) {
// Get post ID from $post_id
if( empty( $post_id ) )
$post_id = get_the_ID();
// If still empty, return false
if( empty( $post_id ) )
return false;
// Set listing price labels
$listing_price_labels = array(
'sold' => __( 'Sold', 'wpsight' ),
'rented' => __( 'Rented', 'wpsight' ),
'request' => __( 'Price on request', 'wpsight' ),
'auction' => __( 'Auction', 'wpsight' ),
);
$listing_price_labels = apply_filters( 'wpsight_get_price_labels', $listing_price_labels );
// Get listing price
$listing_price = wpsight_get_price_value();
// Get custom fields
$custom_fields = get_post_custom( $post_id );
$listing_status = isset( $custom_fields['_price_status'][0] ) ? $custom_fields['_price_status'][0] : false;
$listing_availability = isset( $custom_fields['_price_sold_rented'][0] ) ? $custom_fields['_price_sold_rented'][0] : false;
// Create price output
if( ! empty( $listing_availability ) ) {
// When listing is not available
$sold_rented = ( $listing_status == 'sale' ) ? $listing_price_labels['sold'] : $listing_price_labels['rented'];
// Display sold/rented bold red in admin
$style = is_admin() ? ' style="color:red;font-weight:bold"' : false;
$listing_price = '<span class="listing-price-sold-rented"' . $style . '>' . $sold_rented . '</span><!-- .listing-price-sold-rented -->';
if( is_admin() )
$listing_price .= '<br />' . wpsight_get_price_value();
} elseif( empty( $listing_price ) ) {
// When no price available Price on request
$listing_price = '<span class="listing-price-on-request">' . $listing_price_labels['request'] . '</span><!-- .listing-price-on-request -->';
} elseif( $listing_price == "auction" ) {
// When price field contains 'auction' (case sensitive)
$listing_price = '<span class="listing-price-on-request">' . $listing_price_labels['auction'] . '</span><!-- .listing-price-on-request -->';
}
return apply_filters( 'wpsight_listing_price', $listing_price );
}
I’m sure my syntax must just be wrong, because with that code in place it makes any property with anything at all written into the price field display “auction”.
Can anyone see what I've done wrong?
try:
if( is_admin() ){
$listing_price .= ‘<br />’ . wpsight_get_price_value();
} elseif( empty( $listing_price ) ) {
// When no price available Price on request
$listing_price = ‘<span class=”listing-price-on-request”>’ . $listing_price_labels['request'] . ‘</span><!– .listing-price-on-request –>’;
}
btw its not recommended to use if( is_admin() ) since its only applicable on 1 line.