PHPExcel example of use - phpexcel

I am trying to use PHPExcel lib. I already read some the API, but still didn't figure how to use it correctly.
I'm trying to convert an array, to an excel table.
If I have:
$Array = array(
array('key1' => 'Content1', 'key2' => 'Content2'),
array('key1' => 'Content3', 'key2' => 'Content4')
);
So the output in the excel file will be:
key1 key2
Content1 Content2
Content3 Content4
key1 and key2 as headings.
Can you help? Thank you

Some discussions are here. check it
Example

Here is my code what I did it ...but the scenario here is little different, here the input is the excel file whereas the output is array of array in 'key' => 'value' pairs (as in your case it is vice versa) which is not much of a solution but though it might help you get going.
<?php
include './PHPExcel/IOFactory.php';
$objPHPExcel = PHPExcel_IOFactory::load('campaign.xlsx');
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$highestColumn = $worksheet->getHighestDataColumn();
//Getting highest column with data
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
//Getting highest row with data
$highestRow = $worksheet->getHighestRow();
$header = [];
//For saving all heading from Excel file.
for( $i = 0 ; $i <= $highestColumnIndex ; $i++)
{
$cell = $worksheet->getCellByColumnAndRow($i,1);
$val = $cell->getValue();
$header[] = $val;
}
$completeArray = [];
$value = [];
//For saving header and value pairs in a array
for ($row = 2; $row <= $highestRow; ++ $row) {
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
$value[$header[$col]] = $val;
}
//Inserting that array...
$completeArray[] = $value;
}
}
echo '<pre>';
print_r($completeArray);
echo '</pre>';
So,in your case instead of using all get methods such as getCellByColumnAndRow as in my example you can use
setCellValueByColumnAndRow($column, $row, $value);
You can make help of this resources also
Tutorial here
CheatSheet here

Related

Insert Advanced Custom Fields Rule to post_meta table

I'm inserting custom fields to postmeta table if the post title is equal to "Components" or "Landing page".
Inside my add_post_meta() function I'm getting the serialized data with extra string at the beginning with double quote and at the end double quote with a semicolon.
Expected a:5:{s:5:"param";s:4:"post";s:8:"operator";s:2:"==";s:5:"value";i:3309;s:8:"order_no";i:0;s:8:"group_no";i:1;}
Currently inserting s:110:"a:5:{s:5:"param";s:4:"post";s:8:"operator";s:2:"==";s:5:"value";i:3309;s:8:"order_no";i:0;s:8:"group_no";i:1;}";
Here is my code:
if ($menupost->post_title == "Components" || $menupost->post_title == "Landing Page") {
global $wpdb;
$posttitle = 'Tablet';
$postid_ofacf = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_title = '" . $posttitle . "' and post_type='acf'");
$post_meta = get_post_meta($postid_ofacf, "rule", false);
$post_count = count($post_meta);
$last_array = $post_meta[$post_count - 1];
$insert_acf_rule_meta = array();
foreach ($last_array as $key => $value) {
if ($key == "group_no") {
$value = $value + 1;
}
if ($key == "value") {
$value = $post_id;
}
$insert_acf_rule_meta[$key] = $value;
}
add_post_meta($postid_ofacf, 'rule', serialize($insert_acf_rule_meta));
$get_acf_post_args = array(
'post_title' => 'Tablet',
'post_status' => 'publish',
'post_type' => 'acf'
);
}
How to insert a proper serialized sting as expected.
Like I'm inserting rule of "Tablet" Custom field to the postmeta table for the posts with title "Components" OR "Landing page", I need to insert some more custom fields(Desktop,Mobile) rules to the postmeta table.
Any help may greatly appreciated, thanks in advance.
There is no need to pass the serialized array as a parameter to the add_post_meta function, as it calls serialize function in case an array is given, as stated in the documentation.
Rewrite the line:
add_post_meta($postid_ofacf, 'rule', serialize($insert_acf_rule_meta));
To:
add_post_meta($postid_ofacf, 'rule', $insert_acf_rule_meta);
Hope this helps.

Return Number of published posts in a custom post type

<?php
$counter=1;
$counter_new=0;
$args = array('posts_per_page' =>-1,'orderby' => 'post_date','order' =>'DESC','post_type' => 'interview','post_status' => 'publish',
'suppress_filters' => true );query_posts( $args );while (have_posts($args)) : the_post();
if($counter < 8)
{
$counter++;
}
else
{
$counter_new++;
$counter=1;
}
endwhile;
?>
I saw someone else code to find the number of post, as record increase it is not efficient. What is the right way to do? It looks stupid now.
In case you use WPML wp_count_post() will not show correct count of posts for given language. Use this instead:
$posts = get_posts('post_type=yourcustomposttype&suppress_filters=0&posts_per_page=-1');
$count = count($posts);
echo $count;
Take a look at the wp_count_posts() function.
For your example:
$count_posts = wp_count_posts('interview');
$published_posts = $count_posts->publish;
$published_posts will return the number of published posts in your 'interview' custom post type.
One of the other answers won't work if you have WMPL and translations. The other one will work, but will be very inefficient.
With WPML, try this instead:
function my_count_posts( string $post_type = 'post', string $language_code = '', string $post_status = 'publish' ): int {
global $wpdb;
$default_language_code = apply_filters( 'wpml_default_language', null );
$language_code = $language_code !== '' ? $language_code : $default_language_code;
$translation_param = $default_language_code == $language_code ? "IS NULL" : "= '{$default_language_code}'";
$query = <<<SQL
SELECT COUNT( {$wpdb->prefix}posts.ID )
FROM {$wpdb->prefix}posts
LEFT JOIN {$wpdb->prefix}icl_translations ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}icl_translations.element_id
WHERE {$wpdb->prefix}icl_translations.language_code = '{$language_code}'
AND {$wpdb->prefix}icl_translations.source_language_code $translation_param
AND {$wpdb->prefix}icl_translations.element_type = 'post_{$post_type}'
AND {$wpdb->prefix}posts.post_status = '$post_status'
SQL;
return $wpdb->get_var( $query );
}
You'd use it like this:
// counts published "posts" in the default language
$count = my_count_posts();
// counts posts of `post_type=custom_post_type` in the current language
$count = my_count_posts('custom_post_type', apply_filters( 'wpml_current_language', '' ));

Drupal 7 delete multiple imagefields form

I am building a drupal 7 (7.20) website with a "project" content type which contains multiple image fields (i do not want to use galleries).
I would like to be able to perform a mass delete operation on these fields from the node edit page. From what I have gathered I have to override theme_file_widget_multiple and return a tableselect instead of a table and then use a button plus javascript to delete the images from the database.
Am I missing something obvious ? This seems like alot of work for something so trivial.
EDIT:
I have had some progress with this:
function mytheme_file_widget_multiple($variables) {
$element = $variables ['element'];
$headers = array ();
$headers ['info'] = t ( '' );
$widgets = array ();
foreach ( element_children ( $element ) as $key ) {
$widgets [] = &$element [$key];
}
usort ( $widgets, '_field_sort_items_value_helper' );
$rows [] = array ();
$i = 0;
foreach ( $widgets as $key => &$widget ) {
// Save the uploading row for last.
if ($widget ['#file'] == FALSE) {
$widget ['#description'] = $element ['#file_upload_description'];
continue;
}
$operations_elements = array ();
foreach ( element_children ( $widget ) as $sub_key ) {
if (isset ( $widget [$sub_key] ['#type'] ) && $widget [$sub_key] ['#type'] == 'submit') {
$operations_elements [] = &$widget [$sub_key];
}
}
$information = drupal_render ( $widget );
$rows [$i ++] ['info'] = $information;
}
$output = '';
$output = drupal_render_children ( $element );
$form ['element'] = array (
'#type' => 'tableselect',
'#header' => $headers,
'#options' => $rows,
'#js_select' => TRUE,
'#empty' => t ( 'No data' ),
'#attributes' => array () );
$output .= empty ( $rows ) ? "" : drupal_render ( $form );
return $output;
}
This was included in my theme's template file however the tableselect does not have checkboxes. This is driving me crazy.. Can someone please tell me what I am doing wrong ?
From what I have gathered I have to create a module which overrides the fieldset preprocess functions..
Here are the references:
1) https://drupal.org/node/1905244
This article seems to try to do what you want to.
2) Also check out https://drupal.org/project/views_bulk_operations
this might be useful.
3) if not then you will need to make your own widget:
https://api.drupal.org/api/drupal/modules%21field%21field.module/group/field/7
https://drupal.org/project/examples ( has all the examples you will need )
all the best.

Invalid argument for foreach associative array loop

I've got an invalid argument supplied for my last associative array foreach loop. I am looping through different email addresses and creating an array. Am I doing something wrong? Should I create a null array?
Cheers!
global $wpdb, $wpsc_variations;
$stock_table = $wpdb->prefix . 'postmeta';
$posts_table = $wpdb->prefix . 'posts';
$q = 'SELECT DISTINCT post_id FROM ' . $stock_table . ' WHERE meta_key=\'' . NOTIFY_META . '\' AND meta_value=1';
$q_assoc_arr = $wpdb->get_results($q, ARRAY_A);
foreach($q_assoc_arr as $row) {
$product_id = $row['post_id'];
$product_data = get_post_custom( $product_id );
$product_data['meta'] = maybe_unserialize( $product_data );
foreach ( $product_data['meta'] as $meta_key => $meta_value ) {
$product_data['meta'][$meta_key] = $meta_value[0];
}
if ($product_data['meta']['_wpsc_stock'] > 0) {
foreach (get_post_meta($product_id, NOTIFY_EMAILS_META, true) as $k=>$v) {
$emails[] = $v;
}
Your third foreach relies on the output of get_post_meta, but you're passing true as the 3rd parameter. This tells get_post_meta to return a single value as a string, not an array.
foreach expects an array to iterate over. :)
Note: This part will fail for certain, but your other instances of foreach may also fail if an array is not passed.

wordpress pagination get current page number from url

I need to extract the value of "page" i.e 5 from this url - http://snypher.local/photos/page/5
What should I do to extract it in Wordpress? I am not able to get it from the $_GET super global.
use get_query_var example $page = get_query_var('paged'); in your case it's 5
its work fine i've tested on my current WP (version 3.5.1)
$current_page = max( 1, get_query_var('paged') );
$total_pages = $wp_query->max_num_pages;
echo 'Page '.$current_page.' of '.$total_pages;
Result = Page 3 of 51
function get_url_var($name)
{
$strURL = $_SERVER['REQUEST_URI'];
$arrVals = explode("/",$strURL);
$found = 0;
foreach ($arrVals as $index => $value)
{
if($value == $name) $found = $index;
}
$place = $found + 1;
return $arrVals[$place];
}
$page = get_url_var('page');
I have used this function to get the value of the variable page from the url.
Found a nice solution and I'd like to share it here for I was looking for exactly the same thing!
http://wordpress.org/support/topic/get-current-page-number-for-paginated-posts
So it's like:
<?php echo '(Page '.$page.' of '.$numpages.')'; ?>

Resources