Import data from csv into a specific post - wordpress

I have multiple posts that has multiple custom fields on it. Now i need to add these fields from a excel/csv file. These files contain lots of info about this post. The problem i run into is that i don't see a way to import this content automatically. I don't seem to be able to use wp all import for this because it create a new item for each record and thats not what i want. All records need to be added as a custom field/repeater field.
If anyone has an idea on how to do this it would be much appreciated.
I tried to import this data using WP all import without succes.

function add_some_fields($file_url) {
$data= array_map('str_getcsv', file($file_url));
foreach ($data as $item) {
$post_id = $item[0]; // I hope you have post_id in that CSV file somewhere
$field_name = $item[1] ; // ACF field name IF YOU HAVE IT IN CSV if not set manually, or make an array with names
$col1 = $item[2]; //Value
add_row( $field_name, $col1, $post_id ); //add row (https://www.advancedcustomfields.com/resources/add_row/)
}
}
Call from where you want and how you want, usually I use condition in footer checking if custom GET parameter passed and if Yes then run function.

Related

WordPress ACF Save Post function, need it only to fire when the page saved is custom post type. Or, if field is present?

I am trying to manipulate the my_acf_save_post function to do some maths and update a field with the resulting number. This part is working, the fields full_market_price and example_price are used to work out calculated_price.
I did this some days ago but have now run in a problem whenever trying to save a page, or post that doesn't need this function, and doesn't contain the ACF fields. So every section of the website rather than just the 1 that requires this maths. It results in various errors and I can't save the pages properly.
How can I make this code snippet only work if the page being saved is within custom post type? So it won't break the other pages?
I'm trying something using
if (is_single() && is_post_type('nameofposttype'))
however I can't seem to get it right, PHP not my strongest! Is a better way to ask if the fields does not exist, then do nothing?
Many thanks for any help or ideas,
function my_acf_save_post( $post_id ) {
// get values
$fmp = get_field('full_market_price');
$saPercent = get_field('example_price');
// do something
$examplePrice = ($fmp / 100) * $saPercent;
update_field('calculated_price', $examplePrice, $post_id);
}
add_action('acf/save_post', 'my_acf_save_post', 20);
I just ran into a similar issue. I would do something like:
function my_acf_save_post ($post_id) {
// If not CPT, exit
if (get_post_type($post_id) != 'nameofposttype') {
return;
}
// Remainder of code
...
}
add_action('acf/save_post', 'my_acf_save_post', 20);

WP All Import Pro: Polylang compatibility

I'm trying to import data from an Excel sheet into WordPress with the Pro version of WP All Import. We are using Polylang for multi language support. I wonder how to manage importing the content into the correct language versions. I discovered that there is a hidden taxonomy "language" which I can manually set to "de" for setting language to German. But how do I link corresponding translations? Any ideas how to solve this, maybe with some custom functions? Thank you in advance!
I have found a better solution.
if ( !function_exists( 'pll_save_post_translations' ) ) {
require_once '/include/api.php'; }
$arr = array();
$result = pll_save_post_translations(['en' => 21398, 'ro'=>21396]);
//where 21398 and 21396 are the post_id and 'en' and 'ro' the nicenames of the languages.
Put this code in your functions.php and run it only once (meaning you refresh the page only once as admin after you put it). Then delete the code from functions.php. It does not actually create errors, just don't risk it, don't run it twice.
Before you do that, you must import the products in both (in my case) languages. Meaning you import them in one language (you select one language from the top admin bar) and then in another session you import them in the other language (you select the other language) and also if you see "Show private taxonomies" in WP All import, put one language code there. One for each session. After the products in both languages have been imported, you run the code above to tell WordPress that "this post_id is the translation of that post_id".
I hope it helps.
Ah, and you get the post_id in a nice table which you can edit in excel by exporting the products with Wordpress Export (it is pre-installed when you install WordPress, I think). You find it in Dashboard in Tools/Export.
And put
$result = pll_save_post_translations(['en' => 56465, 'ro'=>654864]);
as many times as you need
$result = pll_save_post_translations(['en' => 9999, 'ro'=>34654]);
$result = pll_save_post_translations(['en' => 98641, 'ro'=>98651]); .
for each correlation.
You can do it easier in Excel, you have the correlating id's on two separate columns then put this formula on the next row
=concatenate("$result = pll_save_post_translations(['en' =>",CELL A1,"
'ro'=>",CELL B1,"]);")
Apply it downwards. Select the column you have just concatenated. Paste it under the code in functions.php. Save. Refresh. Delete code from functions.php. Refresh. Booyah.
Please note that I'm currently using both Polylang and Wp All Import/Export Pro versions.
Also, this is currently not 'outdated' code. It relies on an undocumented feature, that was suggested directly from the wp all import team. I'm speaking simply of the additional parameter $data passed by the pmxi_saved_post action.
That said, I know polylang devs are currently working on an addon for this specific issue. Anyway, I managed to do it in this way, for now:
1 -> when you export data, there are 2 polylang-related fields: languages and post_translations. Export them too.
2 -> when you import your data, on the wpallimport screen, create 2 more custom fields and save the 2 above. See attachment below. Now you've got the translations data with every post.
3 -> set this filter:
global $language_codes;
$language_codes = array( // sample lang data
'italiano' => 'it'
,'english' => 'en'
,'espanol' => 'es'
,'francais' => 'fr'
,'deutsch' => 'de'
);
add_action('pmxi_saved_post', 'set_imports_lang', 10, 2);
// using undocumented param $data
// action firm is the following (in fact, it passes 3 params): do_action( 'pmxi_saved_post', $pid, $rootNodes[$i], $is_update );
function set_imports_lang($post_id, $data){
global $language_codes;
// 'lingue' is italian, I guess it will be 'languages' in english: it's one of the 2 fields we saved before
pll_set_post_language($post_id, $language_codes[sanitize_title($data->lingue)]);
}
At this point you have just set each post's original language, nothing more. Now we have to link translations each other. We'll do this with a function that we have to run ONLY 1 TIME. It will run simply reloading any wp screen/page.
function set_imports_translations(){
global $wpdb;
global $language_codes;
// substitute 'enews' with your own post type
$list = $wpdb->get_results("
SELECT
m.post_id, m.meta_value pll, group_concat(concat_ws(':', m2.meta_value, m.post_id)) ids
FROM
$wpdb->posts p
INNER JOIN $wpdb->postmeta m ON p.ID = m.post_id
INNER JOIN $wpdb->postmeta m2 ON m.post_id = m2.post_id AND m2.meta_key = '_import_language_name'
WHERE
p.post_type = 'enews' AND m.meta_key = '_import_translations_id'
GROUP BY pll
");
// query results are something like this:
// 10258 pll_57e92254c445f 10258:Italiano,10259:English,10260:Español,10261:Français,10262:Deutsch
// 10263 pll_57e922552b8c6 10263:Italiano,10264:English,10265:Español,10266:Deutsch
// 10267 pll_57e9225587124 10267:Italiano
// extract data from the third column string
foreach($list as $item){
$ids = explode(',',$item->ids);
$list = array();
foreach($ids as $id){
$data = explode(':',$id);
$list[$language_codes[sanitize_title($data[0])]] = intval($data[1]);
}
//set the translations
pll_save_post_translations($list);
}
}
set_imports_translations();
That's all. :) Ah, the attachment mentioned above:

Import variables products after export

I have export my variations product from woocomerce using standart WP export stuff, how to import them back?
When I use import WP write to me all done, but in products variations did not appear
It took me hours to figure out why the post_parent field (for WooCommerce product Variations, in my case) wouldn't import using the integrated WordPress Export/Import. I ended up looking in the import plugin files and that's where I found the answer. It turns out it only applies the post_parent field, if the parent ID being referenced is contained in the same import. Which is silly since Products and Variations have to be exported as separate XML files.
Anyway, I temporarily added one line of code to the wordpress-importer.php file to get my import to work. Obviously, you shouldn't go around hacking plugins, but this is what worked for me:
$post_parent = (int) $post['post_parent'];
if ( $post_parent ) {
// if we already know the parent, map it to the new local ID
if ( isset( $this->processed_posts[$post_parent] ) ) {
$post_parent = $this->processed_posts[$post_parent];
// otherwise record the parent for later
} else {
$this->post_orphans[intval($post['post_id'])] = $post_parent;
$post_parent = 0;
}
$post_parent = (int) $post['post_parent']; // ADDED THIS LINE
}
Problem was in field post_parent. I don't know why, but in database this field set 0 and not from .xml file.
My resolve of problem:
Set manually in db parent post id

How to extract the variables out from "add_shortcode" function in Wordpress?

In Wordpress (now in Template Fiile), lets say i have a custom Shortcode function, like:
In the PAGE:
[myshortcode id='1234']
Then, in the Template File:
function parseUserID_func( $atts ){
//parse the $atts here...
$userID = 1234; //now i get the userID is, 1234
}
add_shortcode( 'myshortcode', 'parseUserID_func' );
//now .. echo the value of $userID here? <----------
printout_UserDetails( $userID );
As you can see, how can i get the processed value of $userID variable out from the shortcode function please? (as in the last line)
The $userID is not touchable from the outside.
Actually what i'm trying to do is something like:
Pass an ID from the Page, using [myshortcode id="1234"]
Parse out the id from the shortcode's function. (parseUserID_func above)
When i get the id, i need to pass it to another custom function printout_UserDetails($id){} function (written in the Template File) .. to continue another processing works.
(Something like) then i will print out the USER DETAILS on the Page, from the printout_UserDetails() function.
This is why i need to pass a value from Shortcode, then parse it, then pass the id to my another custom function.
Any help please?
From what I'm understanding you're not trying to generate output with the shortcode, but to save data instead. I would try using custom fields to handle this.
If you need to output the "USER DETAILS" block within the post content (right where the shortcode is written), you should just merge the printout_userDetials logic into the actual shortcode handler function itself (in this case parseUserID_func).

Show up Woocommerce custom fileds into the CSV export

I'm using "Woocommerce CSV Export" plugin and i've just added 2 custom fileds into my WC checkout page, I was wondering if i can add those fileds to the export plugin.
Just add the following code into your "woocommerce-export-csv.php"
add_filter( 'woocommerce_export_csv_extra_columns', 'sites_add_custom_meta', 10);
and the define your function
function sites_add_custom_meta() {
$custom_meta_fields['columns'][] = 'IP Address';
$custom_meta_fields['data'][] = '_customer_ip_address';
return $custom_meta_fields;
}
In this function you have two things you need to define. First, in the columns array you need to define the titles of your custom meta fields and then in the data array you need to define actual meta field name where the data for that field is located at. You need to have the same order in both arrays to be able to have correct information output under right column title.
Source : http://docs.woothemes.com/document/ordercustomer-csv-exporter/#section-4

Resources