How to structure a multi array to process and sort WooCommerce Order Item data? - arrays

How can I extract details from an order into an array, while on the "Order Edit" page and then loop through them?
My array structure isn't correct as can't handle a 3rd item-detail. So each order item somehow needs to be placed into its own sub-array.
Then I want to be able to sort them on item-name and print them out with an echo.
How to achieve the correct array structure to input them and extract?
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'additional_admin_order_data_block_after_shipping_address', 100 );
function additional_admin_order_data_block_after_shipping_address(){
echo '</div><div class="order_data_column order_packing_column">
<h3>' . esc_html__( 'Packing Items', 'woocommerce' ) . '</h3>';
// here goes your code and content
//custom array to list products:
$products_array = array();
$product_tally = 0;
global $post; // <=== Alway at the beginning
// Get an instance of the WC_Order Object
$order = wc_get_order( $post->ID );
// let's decide what order item types we would like to get
$types = array( 'line_item');
// defaults to line_item which allows to get products from order
foreach( $order->get_items( $types ) as $item_id => $item ) {
// order ID
$item_order_id = $item->get_order_id();
// product only and no bundle 'summary' item
if( empty( $item['woosb_ids']) && $item->is_type( 'line_item' ) ) {
// order item name (product title, name of a shipping method or coupon code)
$item_name = $item->get_name();
if ( array_key_exists($item_name, $products_array)) {
$products_array[$item_name] += $item['qty'];
} else {
$products_array[$item_name] = $item['qty'];
}
$product_tally = $product_tally + $item->get_quantity();
}
}
arsort($products_array);
echo '<div class="woocommerce_order_items" id="packing-table">
<div class="thead">
<div class="tr">
<div class="item sortable">Product</div>
<div class="quantity sortable">Qty</div>
</div>
</div>
<div class="tbody" id="order_line_items">';
//display list:
foreach ($products_array as $title => $quantity) {
echo '<div class="lineitem">
<div class="item">';
echo $title.'</div>
<div class="quantity">'.$quantity.'</div>
</div>';
}
echo '<div class="lineitem tally">
<div class="item">Tally of Items</div>
<div class="quantity">'.$product_tally.'</div>
</div>';
echo '</div>
</div>';
}

Related

implode function not working in codeigniter

I want to store a checkbox array value by using implode function.when i stored,the database table value as Array (not a integer value show only array)
This is my view file:
<div class="col-sm-12">
<div>
<label class="form-control-label">Select Asset Type</label><br>
<div class="border-checkbox-section">
<div class="border-checkbox-group border-checkbox-group-primary">
<?php $b=0; foreach($assettype as $assettype_info){ $b++;?>
<input type="checkbox" name="assettype_name[]" class="border-checkbox" value="<?php echo $assettype_info->assettype_name; ?>" id="checkbox<?php echo $b;?>">
<label class="border-checkbox-label" for="checkbox<?php echo $b;?>"><?php echo $assettype_info->assettype_name; ?></label>
<?php } ?>
</div>
</div>
</div>
My Controller:
public function insertassetassign()
{
$employee=$_POST['employee'];
$assettype_name = implode(", ", $_POST['assettype_name']) ;
$assign_date = date("Y-m-d",strtotime($_POST['assign_date']));
$_POST['assetassign_status']='1';
$joinon=date('Y-m-d');
$result = $this->insert->insertrecord('assetassign');
if($result)
{
redirect('assets/assetassignment', 'refresh');
}
}
My Model :
Public function insertrecord($Table)
{
$Inputs=$_POST;
$Inputs["joinon"]=date("Y-m-d");
$Keys=array();
$Values=array();
foreach($Inputs as $Inp_key=>$inp_value)
{
if($Inp_key!="submit" && $Inp_key!="PHPSESSID")
{
$Keys[]= $Inp_key;
$Values[]= "'".$inp_value."'";
}
}
$keys=implode(',',$Keys);
$values=implode(',',$Values);
$qry="insert into ".$Table."(".$keys.") values(".$values.")";
$ack=$this->db->query($qry);
if($ack) return true; else return false;
}
I expected to store a array value as id with comma
DB shows as :
Db shows as
modified in controller to get the answer.
public function insertassetassign()
{
$employee=$_POST['employee'];
$assettype_name = implode(",",$_POST['assettype_name']) ;
$_POST['assettype_name'] = $assettype_name;
$assign_date = date("Y-m-d",strtotime($_POST['assign_date']));
$_POST['assetassign_status']='1';
$joinon=date('Y-m-d');
$result = $this->insert->insertrecord('assetassign');
if($result)
{
redirect('assets/assetassignment', 'refresh');
}
}

wp_query returns only first from variable array

I need to have variable containing array to put inside post__in => array ($variable), but with the posted code wp_query returns only one (the first post id number).
I tried to hardcode 'post__in' => array(24,23,25) and the query displays all three posts but I can't figure out how to make it dynamic (to have post__in => array ($variable)). I suspect there's something with the '' but can't find out.
$selected_ids = '24,23,25'; //needs to be equal to $_POST['selected_ids'];
$args2 = array(
'post_type' => 'specs',
'post__in' => array($selected_ids)
);
$query2 = new WP_Query( $args2 );
if ( $query2->have_posts() ) {
while ( $query2->have_posts() ) {
$query2->the_post();
echo '<li class="col-lg-3">
<div class="col compare-item-field">
<button type="button" class="close" aria-label="Close">
<span aria-hidden="true">×</span>
</button></br>
<p>' . get_the_title( $query2->post->ID ) . '</p>
<p class="text-muted">at ' . get_field( 'myField', $query2->post->ID ) . '</p>
</div>
</li>';
}
// Restore original Post Data
wp_reset_postdata();
}
Currently, 'post__in' => array($selected_ids) is using an array that's got one item in it that's an "ID" of "24,23,25".
That's because $selected_ids = '24,23,25'; is a string. If you're getting '24,23,25' from an input value, you can use PHP's explode() function to turn that string into an array, by exploding it at the commas.
$ids = '24,23,25';
$selected_ids = explode( ',', $ids );
That will return an actual array:
array(3) {
[0]=> string(2) "24"
[1]=> string(2) "23"
[2]=> string(2) "25"
}

WP Custom Post Type - Display taxonomy as CSS class

I have set up a custom post type in wordpress called "Portfolio". The custom post type then has two taxonomy's set up. They are named 'portfolio_categories' and 'portfolio_sector'.
Currently i am using the following code to gather all my 'portfolio_categories' and store them so they can then be outputted as CSS class to be used for filtering.
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$termsArray = get_the_terms( $post->ID, "portfolio_categories" ); //Get the terms for this particular item
$termsString = ""; //initialize the string that will contain the terms
foreach ( $termsArray as $term ) { // for each term
$termsString .= $term->slug.' '; //create a string that has all the slugs
}
?>
Then the code to output the terms as classes is as follows:
<div class="<?php echo $termsString; ?>">
Content goes here
</div>
How would i need to edit my code in order to store the taxonomy 'portfolio_sector' and output them as classes also?
You should also get your others terms data, in your context
<?php
while ( $the_query->have_posts() ) {
$the_query->the_post();
$termsArray = get_the_terms( $post->ID, "portfolio_categories" ); //Get the terms for this particular item#
$termsSectors = get_the_terms( $post->ID, "portfolio_sector" );
$termsString = ""; //initialize the string that will contain the terms
foreach ( $termsSectors as $term ) { // for each term
$termsSector .= $term->slug.' '; //create a string that has all the slugs
}
foreach ( $termsArray as $term ) { // for each term
$termsString .= $term->slug.' '; //create a string that has all the slugs
}
}
Now you can echo this via the var $termsSector.
However, as a hint you can also work with get_the_term_list() to get a list include HTML. Maybe this is easier for you and it is not necessary to loop about the array of the terms.

Drupal Custom Module HTML

So I've only just begun to learn Drupal so If you believe I'm going about this the wrong way, please let me know.
I have a content type called Events. I'm basically just trying to output a snippet of the latest event on the home page. To do this, I've created a custom module following the Drupal tutorial Drupal doc's custom module tutorial
Here's my module's code
<?php
/**
* Implements hook_block_info().
*/
function latest_event_block_info() {
$blocks['latest_event'] = array(
// The name that will appear in the block list.
'info' => t('Latest Event'),
// Default setting.
'cache' => DRUPAL_CACHE_PER_ROLE,
);
return $blocks;
}
/**
* Custom content function.
*
* Set beginning and end dates, retrieve posts from database
* saved in that time period.
*
* #return
* A result set of the targeted posts.
*/
function latest_event_contents(){
//Get today's date.
$today = getdate();
//Calculate the date a week ago.
$start_time = mktime(0, 0, 0,$today['mon'],($today['mday'] - 7), $today['year']);
//Get all posts from one week ago to the present.
$end_time = time();
//Use Database API to retrieve current posts.
$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'event')
->propertyCondition('status', 1) // published == true
->propertyCondition('created', array($start_time, $end_time), 'BETWEEN')
->propertyOrderBy('created', 'DESC') //Most recent first.
->range(0, 1); //ony grab one item
return $query->execute();
}
/**
* Implements hook_block_view().
*
* Prepares the contents of the block.
*/
function latest_event_block_view($delta = '') {
switch ($delta) {
case 'latest_event':
$block['subject'] = t('Latest Event');
if (user_access('access content')) {
// Use our custom function to retrieve data.
$result = latest_event_contents();
$nodes = array();
if (!empty($result['node'])) {
$nodes = node_load_multiple(array_keys($result['node']));
}
// Iterate over the resultset and generate html.
foreach ($nodes as $node) {
//var_dump($node->field_date);
$items[] = array(
'data' => '<p>
<span class="text-color">Next Event</span> ' .
$node->field_date['und'][0]['value'] . ' ' .
'</p>' .
'<p>' .
$node->title . ' ' .
$node->field_location['und'][0]['value'] . ' ' .
'</p>'
);
}
// No content in the last week.
if (empty($nodes)) {
$block['content'] = t('No events available.');
}
else {
// Pass data through theme function.
$block['content'] = theme('item_list', array(
'items' => $items));
}
}
return $block;
}
}
I've added the block to a region, and it renders fine in my template page. However, the events are outputted in a list which is not what I want.
Here's how the block is being rendered in HTML
<div class="item-list">
<ul>
<li class="first last">
<p>
<span class="text-color">Next Event</span> June 23 2016 18:30 - 21:00 </p><p>Cancer Research UK Angel Building, 407 St John Street, London EC1V 4AD
</p>
</li>
</ul>
</div>
So assuming I'm going about this whole thing correctly, how can I modify this blocks html? Thanks!
I think first you need to understand the theme('item_list', ....). This always output a HTML list either UL or OL as given.
If you want to show your content without the HTML list wrapper, you could try this:
/**
* Implements hook_block_view().
*
* Prepares the contents of the block.
*/
function latest_event_block_view($delta = '') {
switch ($delta) {
case 'latest_event':
$block['subject'] = t('Latest Event');
if (user_access('access content')) {
// Use our custom function to retrieve data.
$result = latest_event_contents();
$nodes = array();
if (!empty($result['node'])) {
$nodes = node_load_multiple(array_keys($result['node']));
}
// Iterate over the resultset and generate html.
$output = '';
foreach ($nodes as $node) {
//var_dump($node->field_date);
$output .= '<p>
<span class="text-color">Next Event</span> ' .
$node->field_date['und'][0]['value'] . ' ' .
'</p>' .
'<p>' .
$node->title . ' ' .
$node->field_location['und'][0]['value'] . ' ' .
'</p>';
}
// No content in the last week.
if (empty($output)) {
$block['content'] = t('No events available.');
}
else {
// Pass data through theme function.
$block['content'] = $output;
}
}
return $block;
}
}
That is one way. Another way is to use your own custom them template and use the array to output through that. For eg.
// Pass data to template through theme function.
$block['content'] = theme('latest_event_block_template', $items);
Then define a hook_theme function to get this to a template, like:
function latest_event_theme() {
return array(
'latest_event_block_template' => array(
'arguments' => array('items' => NULL),
'template' => 'latest-event-block-template',
),
);
}
Now, you should have a template at the module's root directory with the name latest-event-block-template.tpl.php. On this template you will be able to get the $items array and adjust the HTML yourself. Don't forget to clear theme registry after creating the template.
Hope it helps!
It's outputting as a list because you are passing $block['content'] the item_list theme function.
What you could do instead is create your own custom theme template using hook_theme. This will let you use custom markup in a custom template file.
After, replace this:
// Pass data through theme function.
$block['content'] = theme('item_list', array('items' => $items));
With this:
// Pass data through theme function.
$block['content'] = theme('my_custom_theme', array('items' => $items));

Quantity is not updating in magento site

we have marketplace multi vendor/seller site. we gave an option for seller to update the product information through frontend.....
As it is marketplace site, we have many sellers.
seller A uploaded product A in frontend [quantity = 20 ]
if seller B have same product , he will assign the same product to his account [quantity = 5 ]
in backend it showing 20 + 5 = 25 quantity.
now the problem is when seller A update the quantity from 20 to 40, it showing 40 in frontend and once we refresh the page, it showing only 35. Means after refreshing it showing quantity of [ Seller A qty- Seller B qty ]
but it should show seller A Quantity.
Before It was working properly , later we did some code changes than we are facing this Problem.
before the qty textfield was looking like as in image :
once we click on "edit " button present in image, it looks like below image :
But we decided to display below image :
so we changed code to look like above image. Than this problem happened.
Before Code : [Everything was working fine ]
<td>
<?php
$selllermpassignproduct=Mage::getModel('mpassignproduct/mpassignproduct')->getAssignProDetails($products->getId());
//Zend_Debug::dump($selllermpassignproduct,null,true);
$stock_item=Mage::getModel('cataloginventory/stock_item')->loadByProduct($products);
$SellerQty=isset($selllermpassignproduct['sellerqty'])?$selllermpassignproduct['sellerqty']:$stock_item->getQty();
$assignqty=isset($selllermpassignproduct['assignqty'])?$selllermpassignproduct['assignqty']:0;
?>
<span id="valueqty_<?php echo $products->getId(); ?>"><?php echo (int) $SellerQty; ?></span>
<input type = "text" id = "qty_<?php echo $products->getId(); ?>" onkeydown="validateNumbers(event)" name = "stock" value = "<?php echo (int) $SellerQty; ?>" style = "display:none"/>
<span class="label wk_action" id="edit_link_<?php echo $products->getId(); ?>">
<img onclick="showField('<?php echo $products->getId(); ?>'); return false;" src="<?php echo $this->getSkinUrl('marketplace/images/icon-edit.png'); ?>"/>
</span>
<p id="updatedqty_<?php echo $products->getId(); ?>" style = "display:none;color:red;">Updated</p>
<br/>
<button id="update_button_<?php echo $products->getId(); ?>" class="buttons" onclick="updateField('<?php echo $products->getId(); ?>',<?php echo $assignqty;?>); return false;" style="display:none" >
<span><span style="font-size:12px;"><?php echo $helper->__('Update') ?></span></span>
</button>
<button id="reset_button_<?php echo $products->getId(); ?>" type="reset" class="cancel" onclick="hideReset('<?php echo $products->getId(); ?>'); return false;" style="display:none" >
<span><span><?php echo $helper->__('Cancel') ?></span></span>
</button>
Script
function hideReset(product_id) {
var qtyId='#qty_'+ product_id;
var editLink="#edit_link_"+ product_id;
var updateButton="#update_button_"+ product_id;
var resetButton="#reset_button_"+ product_id;
$wk_jq(qtyId).hide();
$wk_jq(editLink).show();
$wk_jq(updateButton).hide();
$wk_jq(resetButton).hide();
}
function updateField(product_id,assignqty)
{
var qtyId = '#qty_'+ product_id;
var valueId = '#valueqty_'+ product_id;
var updatedqty = '#updatedqty_'+ product_id;
var editLink = "#edit_link_"+ product_id;
var updateButton = "#update_button_"+ product_id;
var resetButton = "#reset_button"+ product_id;
var url ='<?php echo Mage::getUrl('marketplace/marketplaceaccount/updateField/')?>';
$wk_jq(qtyId).toggle()
$wk_jq(editLink).hide();
$wk_jq(updateButton).show();
$wk_jq(resetButton).show();
$qty = $wk_jq(qtyId).val();
jQuery(valueId).html($qty);
hideReset(product_id);
var tmpQty=assignqty+ parseInt($qty) ;
new Ajax.Request(url, {
method: 'post',
parameters: {id: product_id, qty: tmpQty},
onComplete: function (transport) {
//alert(transport.responseText);
jQuery(priceId).val($price);
// $wk_jq(priceId).setValue($price);
jQuery(updatedqty).show().delay(2000).fadeOut();
$updateButton.prop('disabled', false);
// $wk_jq(qtyId).setValue($qty);
}
});
}
Present code
In the above code, we comment some lines and we replaced some codes as below.
commented code
<!-- <img onclick="showField('<?php echo $products->getId(); ?>'); return false;" src="<?php echo $this->getSkinUrl('marketplace/images/icon-edit.png'); ?> -->
**script**
//$wk_jq(qtyId).toggle()
//$wk_jq(updateButton).show();
//hideReset(product_id);
//jQuery(updatedqty).show().delay(2000).fadeOut();
Replaced code 1 )
<input type = "text" id = "qty_<?php echo $products->getId(); ?>" onkeydown="validateNumbers(event)" name = "stock"
value = "<?php echo (int) $SellerQty; ?>" style = "display:none"/>
to
<input type = "text" id = "qty_<?php echo $products->getId(); ?>" onkeydown="validateNumbers(event)"
name = "stock" class="ama1" value = "<?php echo (int) $SellerQty; ?>" />
Replaced code 2)
var tmpQty=assignqty+ parseInt($qty) ;
new Ajax.Request(url, {
method: 'post',
parameters: {id: product_id, qty: tmpQty},
to
var tmpQty=parseInt(assignqty)+ parseInt($qty) ;
new Ajax.Request(url, {
method: 'post',
parameters: {id: product_id, qty: $qty},
I found solution for 1st problem.
public function massupdatesellerproAction(){
if($this->getRequest()->isPost()){
if(!$this->_validateFormKey()){
$this->_redirect('marketplace/marketplaceaccount/myproductslist/');
}
$ids= $this->getRequest()->getParam('product_mass_update');
$price= $this->getRequest()->getParam('price');
$special= $this->getRequest()->getParam('specialprice');
$i=1;
foreach ($ids as $key => $value) {
$i=$i+1;
$qty = $this->getRequest()->getParam('stock'.$i);
$product = Mage::getModel('catalog/product')->load($value);
$product->setPrice($price[$key]);
$product->setSpecialPrice($special[$key]);
//$product->setQty($qty);
$product->save();
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($value);
$stockItem->setData('manage_stock', 1);
$stockItem->setData('qty', $qty);
$stockItem->save();
}
Mage::getSingleton('core/session')->addSuccess( Mage::helper('marketplace')->__('Products has been sucessfully deleted from your account'));
$this->_redirect('marketplace/marketplaceaccount/myproductslist/');
}}

Resources