Attempting to POST a certain number of variables based on the number of images in a folder. The variables are based on numbers found in fields with input name "Pano__000nheading" when n is the number in the current loop. I believe i have the code working properly on the page which is getting the values just need help if you see any flaws here is my code:
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$id = substr( $url, strrpos( $url, '&' )+1 );
$dirname = "../wp-content/themes/Explorable/".$id."/";
$images = glob($dirname."*.jpg");
// Open a known directory, and proceed to read its contents
foreach($images as $image) {
$imageNameLong = substr($image, -14);
$imageName = substr($imageNameLong,0 , -4);
if ( isset( $_POST[$imageName.'links'] ) )
update_post_meta( $post_id, '_'.$imageName.'links', sanitize_text_field( $_POST[$imageName.'links'] ) );
else
delete_post_meta( $post_id, '_'.$imageName.'links' );
if ( isset( $_POST[$imageName.'heading'] ) )
update_post_meta( $post_id, '_'.$imageName.'heading', sanitize_text_field( $_POST[$imageName.'heading'] ) );
else
delete_post_meta( $post_id, '_'.$imageName.'heading' );
};
Related
I'm trying to generate a unique random value from an array and store it in another array so it can't be used again.
I've managed to generate the random value based on a meta field but I'm not sure how I would go about making this unique and ensuring the same values aren't being generated again. I've created an empty array $tickethistory to save the values into. Is it possible the next time it runs to run a validation check so the $lottery_max_tickets don't include the $tickethistory values?
I'm using the function below which returns the number and I', calling it when customers purchase a product in Woocommerce.
function add_lottery_ticket_number( $postid ) {
$tickethistory = array();
$lottery_max_tickets = get_post_meta( $postid, '_max_tickets', true );
$max_tickets = range(1, $lottery_max_tickets);
$ticketallocated = array_rand($max_tickets, 1);
$tickethistory[] = $ticketallocated;
return $ticketallocated;
}
for ( $i = 0; $i < $item_meta['_qty'][0]; $i++ ) {
add_post_meta( $product_id, '_participant_id', $order->get_user_id() );
$participants = get_post_meta( $product_id, '_lottery_participants_count', true ) ? get_post_meta( $product_id, '_lottery_participants_count', true ) : 0;
update_post_meta( $product_id, '_lottery_participants_count', intval( $participants ) + 1 );
$this->add_lottery_to_user_metafield( $product_id, $order->get_user_id() );
$ticketnumber = $this->add_lottery_ticket_number($product_id);
$log_ids[] = $this->log_participant( $product_id, $order->get_user_id(), $ticketnumber, $order_id, $item );
}
As you can see here, you can use storing array in the metadata - in your case, the tickethistory array.
But, for your case I would take different approach - create ticket options once and assign the first element each time.
Consider the following:
function add_lottery_ticket_number( $postId ) {
if (metadata_exists('post', $postId, 'optionsToGive')) {
$ticketOptions = get_post_meta( $postId, 'optionsToGive', true );
} else {
$lottery_max_tickets = get_post_meta( $postid, '_max_tickets', true );
$ticketOptions = range(1, $lottery_max_tickets);
shuffle($ticketOptions ); //random order of all number
}
$ticketAllocated = array_shift($ticketOptions); //take the first element
update_post_meta( $postId, 'optionsToGive', $ticketOptions ); //update all the rest
return $ticketAllocated;
}
Notice, if all numbers has been assign this will return null.
As I never tested this code please consider it as pseudo.
I am learning PHP, so forgive me if my question is somewhat silly.
I have created a form to update records in my db, which includes changing your name, age and image. When I update a record without changing the image it deletes the image (base64 string) from the updated row.
How can I check if an image has been changed or not, and if not: keep the present one unchanged or put into other words, not update that specific field. here is my php script for the update:
if( !is_null( $db ) && array_key_exists( 'edit_person', $_POST ) ):
$pn = filter_var( trim( $_POST['name'] ), FILTER_SANITIZE_STRING );
$n = filter_var( trim($_POST['age'] ), FILTER_SANITIZE_STRING );
// check if another image has been uploaded
$img = filter_var( trim($_POST['img'] ), FILTER_SANITIZE_STRING );
// if not: don't update img
$id = filter_var( trim ( $_POST['id'] ), FILTER_SANITIZE_NUMBER_INT );
update_person( $db, $id, $img, $n, $pn );
endif;
the update_person function:
function update_person( &$db, $id, $img, $age, $name ){
if( is_null( $db ) ) return '';
$sql = "
UPDATE
xxx
SET
xxx.name = :name,
xxx.age = :age,
xxx.img = :img
WHERE
xxx.id = :id
";
$vraag = $db->prepare( $sql );
$vraag->bindValue( ':name', $name, PDO::PARAM_STR );
$vraag->bindValue( ':age', $age, PDO::PARAM_STR );
$vraag->bindValue( ':img', $img, PDO::PARAM_STR );
$vraag->bindValue( ':id', $id, PDO::PARAM_INT );
$vraag->execute();
}
Any help is very much appreciated!
Try the below code. If the $img variable is not set, do not update the image column in table
if( !is_null( $db ) && array_key_exists( 'edit_person', $_POST ) ):
$pn = filter_var( trim( $_POST['name'] ), FILTER_SANITIZE_STRING );
$n = filter_var( trim($_POST['age'] ), FILTER_SANITIZE_STRING );
// check if another image has been uploaded
$img = filter_var( trim($_POST['img'] ), FILTER_SANITIZE_STRING );
// if not: don't update img
$id = filter_var( trim ( $_POST['id'] ), FILTER_SANITIZE_NUMBER_INT );
if(!empty($img) && $img != '') :
update_person( $db, $id, $n, $pn );
else:
update_person( $db, $id, $img, $n, $pn );
endif;
endif;
Hope this helps.
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);
I am trying to add the woocommerce product SKU to the URL of the product. I have followed this guide (http://www.themelocation.com/how-to-add-sku-to-product-url-in-woocommerce/) which works, however I need the SKU to come before the slug.
Like this:
http://test.com/shop/category/sku-product
I have amended the code in the above link to successfully get this order in the wordpress admin area, however as you might predict, it is causing all the products to 404.
How do I go about fixing this? Some kind of htaccess redirect rule?
Here is my amended code:
function custom_meta_permalink( $link, $post ){
$post_meta = get_post_meta( $post->ID, '_sku', true );
if( empty( $post_meta ) || !is_string( $post_meta ) )
$post_meta = '';
$link = str_replace( '!!custom_field_placeholder!!', $post_meta, $link );
return $link;
}
add_filter( 'post_link', 'custom_meta_permalink', 10, 2 );
function append_sku_string( $link, $post ) {
$post_meta = get_post_meta( $post->ID, '_sku', true );
if ( 'product' == get_post_type( $post ) ) {
$end = substr($link, strrpos($link, '/') + 1);
$beg = substr($link, 0, strrpos( $link, '/' ));
$link = $beg . '/' .$post_meta.'-'.$end;
return $link;
}
}
add_filter( 'post_type_link', 'append_sku_string', 1, 2 );
I want to change the slug of a post with a custom field.
In example, if the custom field is "keyword" my post link will become: mysite.com/keyword.
I wrote this script in fonction.php:
function change_default_slug($id) {
// get part number
$partno = get_post_meta( $id, 'partno', true );
$post_to_update = get_post( $id );
// prevent empty slug, running at every post_type and infinite loop
if ( $partno == '' )
return;
$updated_post = array();
$updated_post['ID'] = $id;
$updated_post['post_name'] = $partno;
wp_update_post( $updated_post ); // update newly created post
}
add_action('save_post', 'change_default_slug');
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
add_meta_box( 'my-meta-box-id', 'My First Meta Box', 'cd_meta_box_cb', 'post', 'normal', 'high' );
}
function cd_meta_box_cb( $post )
{
$values = get_post_custom( $post->ID );
$text = isset( $values['my_meta_box_text'] ) ? esc_attr( $values['my_meta_box_text'][0] ) : '';
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>
<p>
<label for="my_meta_box_text">Text Label</label>
<input type="text" name="my_meta_box_text" id="my_meta_box_text" value="<?php echo $text; ?>" />
</p>
<?php
}
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_save( $post_id )
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
// now we can actually save the data
$allowed = array(
'a' => array( // on allow a tags
'href' => array() // and those anchords can only have href attribute
)
);
// Probably a good idea to make sure your data is set
if( isset( $_POST['my_meta_box_text'] ) )
update_post_meta( $post_id, 'my_meta_box_text', wp_kses( $_POST['my_meta_box_text'], $allowed ) );
}
$partno = get_post_meta($post->ID,'my_meta_box_text',true);
echo $partno;
This script return me "Fatal error: Maximum execution time of 30 seconds exceeded". But it seems it work because my slug change. Any idea about this issue?
The 'save_post' action gets called by wp_update_post(), so your change_default_slug() function causes an infinite loop. You need to perform a check within change_default_slug() and bail out if the function has already been called:
function change_default_slug($id) {
static $beentheredonethat = false;
if ($beentheredonethat) return;
$beentheredonethat = true;
//do your stuff and save the post...
}