XML with multiple roots - php

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);

Related

Sorting Wordpress Posts by Word count without Tags

I'm trying to sort posts on the Manage Posts page by word count. I have the column set up and the count is displayed correct, stripped of all tags, html, etc. However, once I sort it, the posts-orderby filter still includes the tags. So if I have one post that is 1000 words without tags, but 1100 with tags, the sorting function views it as bigger that the post that is 1050 without tags and 1060 with tags. Is there any way to apply all of the code stripping used in the "//Strips content and counts words" section to the final orderby logic?
// Add Length Column
add_filter('manage_post_posts_columns', function ( $columns )
{
$_columns = [];
foreach( (array) $columns as $key => $label )
{
$_columns[$key] = $label;
if( 'title' === $key )
$_columns['ryu_post_content_length'] = __( 'Length' );
}
return $_columns;
} );
//Strips content and counts words
function fsj_count_content_words( $content ) {
$decode_content = html_entity_decode( $content );
$filter_shortcode = strip_shortcodes( $decode_content );
//removes embedded video and images code
$remove_videos = preg_replace('/<figure class="wp-block-embed is-type-video is-provider-tiktok">(.*?)<\/figure>/s', '', $filter_shortcode);
$remove_images = preg_replace('/<div class="wp-block-chroma-blocks-media-upload none">(.*?)<\/div>/s', '', $filter_shortcode);
//strips the html tags
$strip_tags = wp_strip_all_tags( $remove_images, true );
//counts the words
$count = str_word_count( strip_shortcodes($strip_tags) );
return $count;
}
// Fill Column With Word Counts
add_action( 'manage_post_posts_custom_column', function ( $column_name, $post_id )
{
if ( $column_name == 'ryu_post_content_length')
echo fsj_count_content_words(get_post( $post_id )->post_content);
//echo str_word_count( wp_strip_all_tags( get_post( $post_id )->post_content ) );
}, 10, 2 );
// Make Column Orderable
add_filter( 'manage_edit-post_sortable_columns', function ( $columns )
{
$columns['ryu_post_content_length'] = 'ryu_post_content_length';
return $columns;
} );
// Order Through Proper Filter
add_filter( 'posts_orderby', function( $orderby, WP_Query $q )
{
$_orderby = $q->get( 'orderby' );
$_order = $q->get( 'order' );
if(
is_admin()
&& $q->is_main_query()
&& 'ryu_post_content_length' === $_orderby
&& in_array( strtolower( $_order ), [ 'asc', 'desc' ] )
) {
global $wpdb;
$orderby = " LENGTH( {$wpdb->posts}.post_content ) " . $_order . " ";
}
return $orderby;
}, 10, 2 );

Remove Component/Variant in Order Invoice PDF in Woocommerce

I Hope are you okay.
Today I have problems with I open order invoice pdf in admin after products list have components.
I Remove all components as well
I am using woocommerce-pdf-invoices-packing-slips plugin.
Below is my product URL :
https://www.pcguru.lt/produktas/amd-home-guru/
My Invoice PDF screenshot as well.
How can I remove it?
I Searching Google but couldn't Found Anything.
After Code Debugging Step by Step, That's are Found Successfully.
File Path:
/wp-content/plugins/woocommerce-pdf-invoices-packing-slips/includes/documents/abstract-wcpdf-order-document-methods.php
public function get_order_items() {
$items = $this->order->get_items();
$data_list = array();
if( sizeof( $items ) > 0 ) {
foreach ( $items as $item_id => $item ) {
//Find Child Product Of Composite Product
global $wpdb;
$post_id = $wpdb->get_row("SELECT meta_value FROM pcg_woocommerce_order_itemmeta WHERE (meta_key = 'wooco_ids' AND order_item_id = '". $item_id ."')");
if($post_id->meta_value !=''){
$main_id = str_replace('/1/', '', $post_id->meta_value);
$data_ids = explode(",",$main_id);
}
//END Custom Code
$data = array();
// Set the item_id
$data['item_id'] = $item_id;
// Set the id
$data['product_id'] = $item['product_id'];
$data['variation_id'] = $item['variation_id'];
// Compatibility: WooCommerce Composit Products uses a workaround for
// setting the order before the item name filter, so we run this first
if ( class_exists('WC_Composite_Products') ) {
$order_item_class = apply_filters( 'woocommerce_order_item_class', '', $item, $this->order );
}
// Set item name
$data['name'] = apply_filters( 'woocommerce_order_item_name', $item['name'], $item, false );
// Set item quantity
$data['quantity'] = $item['qty'];
//$data['product_desc'] = $item->get_product(); // Get the WC_Product objec
//echo '<pre>'; print_r($product); echo '</pre>'; die;
// Set the line total (=after discount)
$data['line_total'] = $this->format_price( $item['line_total'] );
$data['single_line_total'] = $this->format_price( $item['line_total'] / max( 1, abs( $item['qty'] ) ) );
$data['line_tax'] = $this->format_price( $item['line_tax'] );
$data['single_line_tax'] = $this->format_price( $item['line_tax'] / max( 1, abs( $item['qty'] ) ) );
$data['tax_rates'] = $this->get_tax_rate( $item, $this->order, false );
$data['calculated_tax_rates'] = $this->get_tax_rate( $item, $this->order, true );
// Set the line subtotal (=before discount)
$data['line_subtotal'] = $this->format_price( $item['line_subtotal'] );
$data['line_subtotal_tax'] = $this->format_price( $item['line_subtotal_tax'] );
$data['ex_price'] = $this->get_formatted_item_price( $item, 'total', 'excl' );
$data['price'] = $this->get_formatted_item_price( $item, 'total' );
$data['order_price'] = $this->order->get_formatted_line_subtotal( $item ); // formatted according to WC settings
// Calculate the single price with the same rules as the formatted line subtotal (!)
// = before discount
$data['ex_single_price'] = $this->get_formatted_item_price( $item, 'single', 'excl' );
$data['single_price'] = $this->get_formatted_item_price( $item, 'single' );
// Pass complete item array
$data['item'] = $item;
// Get the product to add more info
if ( is_callable( array( $item, 'get_product' ) ) ) {
$product = $item->get_product();
} else {
$product = $this->order->get_product_from_item( $item );
}
// Checking fo existance, thanks to MDesigner0
if( !empty( $product ) ) {
// Thumbnail (full img tag)
$data['thumbnail'] = $this->get_thumbnail( $product );
$data['get_parent_id'] = is_callable( array( $product, 'get_parent_id' ) ) ? $product->get_parent_id() : '';
// Set item SKU
$data['sku'] = is_callable( array( $product, 'get_sku' ) ) ? $product->get_sku() : '';
// Set item weight
$data['weight'] = is_callable( array( $product, 'get_weight' ) ) ? $product->get_weight() : '';
// Set item dimensions
$data['dimensions'] = $product instanceof \WC_Product ? WCX_Product::get_dimensions( $product ) : '';
// Pass complete product object
$data['product'] = $product;
} else {
$data['product'] = null;
}
// Set item meta
if (function_exists('wc_display_item_meta')) { // WC3.0+
$data['meta'] = wc_display_item_meta( $item, array(
'echo' => false,
) );
} else {
if ( version_compare( WOOCOMMERCE_VERSION, '2.4', '<' ) ) {
$meta = new \WC_Order_Item_Meta( $item['item_meta'], $product );
} else { // pass complete item for WC2.4+
$meta = new \WC_Order_Item_Meta( $item, $product );
}
$data['meta'] = $meta->display( false, true );
}
if (!in_array($data['product_id'], $data_ids)) {
$data_list[$item_id] = apply_filters( 'wpo_wcpdf_order_item_data', $data, $this->order, $this->get_type());
}
}
}
//echo '<pre>'; print_r($data_list); echo '</pre>'; die;
return apply_filters( 'wpo_wcpdf_order_items_data', $data_list, $this->order, $this->get_type() );
}
Solution Screenshot:
I am very happy because solution are completed.
Also Thanks to all helping guys

displaying all categories/terms applicable to single page in javo directory

I am using javo directory theme and I cannot seem to figure this out. On the map page where there are a list of listings (after user does a search by category). However, only the first category is being displayed and I need all the categories of each listing to be displayed. Displaying only 1 category defeats the purpose of being able to search by category. Here is the code, let me know if you need other code to better understand what I am trying to do but I know the change has to be within this area. I have looked everywhere for a solution which is why I need some help Thanks a lot!
public function get_meta( $key, $default_value=false ) {
$strOutput = get_post_meta( $this->post_id, $key, true );
return empty( $strOutput ) ? $default_value : $strOutput;
}
public function m( $key, $value=false ){
return $this->get_meta( $key, $value );
}
public function get_term( $taxonomy=false, $sep=', ' )
{
$output_terms = Array();
if( $terms = wp_get_object_terms( $this->post_id, $taxonomy, Array( 'fields' => 'names' ) ) )
{
$output_terms = is_array( $terms ) ? join( $sep, $terms ) : null;
$output_terms = trim( $output_terms );
// $output_terms = substr( $output_terms, 0, -1 );
}else{
$output_terms = '';
}
return $output_terms;
}
public function c( $taxonomy=false, $default='', $single=true, $sep=', ' )
{
$strTerms = $this->get_term( $taxonomy, $sep );
if( $single && !empty( $strTerms ) ) {
$strTerms = #explode( $sep, $strTerms );
$strTerms = isset( $strTerms[0] ) ? $strTerms[0] : '' ;
}
return empty( $strTerms ) ? $default : $strTerms;
}
public function category() {
return $this->c(
apply_filters( 'jvfrm_spot_' . get_class( $this ) . '_featured_tax', 'category', $this->post_id ),
apply_filters( 'jvfrm_spot_' . get_class( $this ) . '_featured_no_tax', __( "No Category", 'javo' ), $this->post_id )
);
}

Add currency symbol to my value that is outputted in a php array

I’ve got the following answer from a question I posted in WordPress Stack Exchange, but how do I show the currency symbol (£) before the value of $givingback_details_funds?
$giving_back = array();
$givingback_details_funds = get_post_meta( $post->ID,'givingback_details_funds', true );
if ( $givingback_details_funds ) {
$giving_back[] = $givingback_details_funds;
}
$givingback_details_days = get_post_meta( $post->ID, 'givingback_details_days', true );
if ( $givingback_details_days ) {
$giving_back[] = _n( 'one working day', $givingback_details_days. ' working days', $givingback_details_days );
}
if ( ! empty( $giving_back ) ) {
echo 'the team donated' . implode( ' and ', $giving_back );
}
What do you even mean? so you cant use this?
$giving_back = array();
$givingback_details_funds = get_post_meta( $post->ID,'givingback_details_funds', true );
if ( $givingback_details_funds ) {
$giving_back[] = $givingback_details_funds;
}
$givingback_details_days = get_post_meta( $post->ID, 'givingback_details_days', true );
if ( $givingback_details_days ) {
$giving_back[] = _n( 'one working day', $givingback_details_days. ' working days', $givingback_details_days );
}
if ( ! empty( $giving_back ) ) {
echo 'the team donated £' . implode( ' and £', $giving_back );
}
or this: EDITED
$giving_back = array();
$givingback_details_funds = get_post_meta( $post->ID,'givingback_details_funds', true );
if ( $givingback_details_funds ) {
$giving_back[] = $givingback_details_funds;
}
$givingback_details_days = get_post_meta( $post->ID, 'givingback_details_days', true );
if ( $givingback_details_days ) {
$giving_back[] = _n( 'one working day', $givingback_details_days. ' working days', $givingback_details_days );
}
$giving_back2 = array_map("mapper",$giving_back);
if ( ! empty( $giving_back2 ) ) {
echo 'the team donated' . implode( ' and ', $giving_back2 );
}
function mapper($a){
return '£'.$a;
}
Or if you are not gonna use the $giving_back again like for only having numbers you can also use this. as – Hamza Abdaoui said.
$giving_back[] = '£ '.$givingback_details_funds;

Get daily orders count in Woocommerce

I want to get daily order count of daily whenever an order is posted. I wrote the below code to give a notification on slack whenever there is an order. As a result of displaying $result it showing the current order amount rather than the total order count of the day.
function wp_slack_woocommerce_order_status_completed2( $events ) {
$events['woocommerce_order_status_processing'] = array(
// Action in WooCommerce to hook in to get the message.
'action' => 'woocommerce_order_status_processing',
// Description appears in integration setting.
'description' => __( 'Whenever we receive an order', 'slack-woocommerce' ),
// Message to deliver to channel. Returns false will prevent
// notification delivery.
'message' => function( $order_id ) {
$order = wc_get_order( $order_id );
$date = is_callable( array( $order, 'get_date_completed' ) )
? $order->get_date_completed()
: $order->completed_date;
$url = add_query_arg(
array(
'post' => $order_id,
'action' => 'edit',
),
admin_url( 'post.php' )
);
$user_id = is_callable( array( $order, 'get_user_id' ) )
? $order->get_user_id()
: $order->user_id;
if ( $user_id ) {
$user_info = get_userdata( $user_id );
}
if ( ! empty( $user_info ) ) {
if ( $user_info->first_name || $user_info->last_name ) {
$username = esc_html( ucfirst( $user_info->first_name ) . ' ' . ucfirst( $user_info->last_name ) );
} else {
$username = esc_html( ucfirst( $user_info->display_name ) );
}
} else {
$billing_first_name = is_callable( array( $order, 'get_billing_first_name' ) )
? $order->get_billing_first_name()
: $order->billing_first_name;
$billing_last_name = is_callable( array( $order, 'get_billing_last_name' ) )
? $order->get_billing_last_name()
: $order->billing_last_name;
if ( $billing_first_name || $billing_last_name ) {
$username = trim( $billing_first_name . ' ' . $billing_last_name );
} else {
$username = __( 'Guest', 'slack-woocommerce' );
}
}
global $wpdb;
$date_from = '2018-02-27';
$date_to = '2018-02-28';
$post_status = implode("','", array('wc-processing', 'wc-completed') );
$result = $wpdb->get_results( "SELECT count(*) as total FROM $wpdb->posts
WHERE post_type = 'shop_order'
AND post_status IN ('{$post_status}')
AND post_date BETWEEN '{$date_from} 00:00:00' AND '{$date_to} 23:59:59'
");
// Remove HTML tags generated by WooCommerce.
add_filter( 'woocommerce_get_formatted_order_total', 'wp_strip_all_tags', 10, 1 );
$total = html_entity_decode( $order->get_formatted_order_total() );
remove_filter( 'woocommerce_get_formatted_order_total', 'wp_strip_all_tags', 10 );
//$data2=WC_API_Reports::get_sales_report( );
// Returns the message to be delivered to Slack.
return apply_filters( 'slack_woocommerce_order_status_completed_message',
sprintf(
__( 'Reveived new order with amount *%1$s*. Made by *%2$s* on *%3$s*. <%4$s|See detail> %s', 'slack-woocommerce' ),
$total,
$username,
$date,
$url,
$resullt
),
$order
);
},
);
return $events;
}
add_filter( 'slack_get_events', 'wp_slack_woocommerce_order_status_completed2' );
To get the daily order count you can use this custom function that will return the order count for the current day or the order count for a specific defined date:
function get_daily_orders_count( $date = 'now' ){
if( $date == 'now' ){
$date = date("Y-m-d");
$date_string = "> '$date'";
} else {
$date = date("Y-m-d", strtotime( $date ));
$date2 = date("Y-m-d", strtotime( $date ) + 86400 );
$date_string = "BETWEEN '$date' AND '$date2'";
}
global $wpdb;
$result = $wpdb->get_var( "
SELECT DISTINCT count(p.ID) FROM {$wpdb->prefix}posts as p
WHERE p.post_type = 'shop_order' AND p.post_date $date_string
AND p.post_status IN ('wc-on-hold','wc-processing','wc-completed')
" );
return $result;
}
Code goes in function.php file of your active child theme (or theme). Tested and works.
USAGE:
1) To get the orders count for the current date:
$orders_count = get_daily_orders_count();
2) To get the orders count for a specific date (with a format like 2018-02-28):
// Get orders count for february 25th 2018 (for example)
$orders_count = get_daily_orders_count('2018-02-25');

Categories