Import taxanomy terms - wordpress

Hi I am importing a csv file, where one of the columns is representing the taxonomy term names separated with ; delimiter.
The code I have is the following:
public function save_post($post,$meta,$terms,$thumbnail,$is_update) {
// Separate the post tags from $post array
if (isset($post['post_tags']) && !empty($post['post_tags'])) {
$post_tags = $post['post_tags'];
unset($post['post_tags']);
}
// Special handling of attachments
if (!empty($thumbnail) && $post['post_type'] == 'attachment') {
$post['media_file'] = $thumbnail;
$thumbnail = null;
}
// Add or update the post
if ($is_update) {
$h = RSCSV_Import_Post_Helper::getByID($post['ID']);
$h->update($post);
} else {
$h = RSCSV_Import_Post_Helper::add($post);
}
// Set post tags
if (isset($post_tags)) {
$h->setPostTags($post_tags);
}
// Set meta data
$h->setMeta($meta);
// Set terms
foreach ($terms as $key => $value) {
$h->setObjectTerms($key, $value);
}
// Add thumbnail
if ($thumbnail) {
$h->addThumbnail($thumbnail);
}
return $h;
}
public function setObjectTerms($taxonomy, $terms)
{
$post = $this->getPost();
if ($post instanceof WP_Post) {
wp_set_object_terms($post->ID, $terms, $taxonomy);
} else {
$this->addError('post_is_not_set', __('WP_Post object is not set.', 'really-simple-csv-importer'));
}
}
The $key is the taxanomy ex: Col and the value is the actual name ex: Fiction Books
Any idea why the taxanomy terms are not ticked when the importation is complete?

Related

How do I output content at the right point from a WordPress plugin?

I'm creating a WordPress plugin for a specific site, which needs to read a feed from another site and display the contents (nicely parsed). The problem I'm having is that I can't figure out how to display the resulting HTML.
I have the following:
Main file (feed-import.php):
/*
Plugin Name: etc
*/
class FeedImport {
private $feedData = "";
private $jsonData;
public function __construct(){
// hook shortcode
add_shortcode('myshortcodename' , array(&$this , 'shortcodeExecute'));
}
// Read shortcode params
public function shortcodeExecute($atts , $content = ""){
if(!class_exists('ParseJSON')) {
require_once plugin_dir_path( __FILE__ ) . 'class-parse-json.php';
}
// Get feed data
$response = wp_remote_get( 'https://feedurl.com' );
if(isset($response['body']) && !empty($response['body'])) {
$this->feedData = $response['body'];
}
// Decode feed data
$this->jsonData = json_decode($this->feedData);
// Parse feed data
$parseJSONObject = new ParseJSON($this->jsonData);
$output = $parseJSONObject->buildHTML();
}
function getOutput() {
return $this->output;
}
}
$feedImport = new FeedImport();
function add_the_feed ( $content ) {
if ( is_page() ) {
return $content . '<p>html content goes here.</p>';
}
}
add_filter( 'the_content', 'add_the_feed');
class-parse-json.php:
class ParseJSON {
private $jsondata = "";
public function __construct($jsonData) {
$this->jsondata = $jsonData;
}
public function buildHTML(){
$html = "<div>";
foreach($this->jsondata as $key => $value) {
$html .= "<div>";
$html .= " <a href='" . $value->html_url . "'>";
$html .= $value->name;
$html .= "</a>";
$html .= " </div>";
}
$html .= "</div>";
return $html;
}
}
(I've left out details of error checking etc for clarity).
This works fine - it adds the text 'html content goes here.' at the end of each page. What I can't figure out is how to replace 'html content goes here' with the actual html content - ie the value of output.
I tried changing add_the_feed to:
function add_the_feed ( $content ) {
if ( is_page() ) {
return $content . $feedImport->getOutput();
}
}
but then I get the error:
Notice: Undefined variable: feedImport
How do I achieve this?
This is a variable scope issue. The add_the_feed() function does not have access to the $feedImport variable. There are two ways to fix this:
Include $feedImport = new FeedImport() in your function.
Use a singleton and create a static instance method (outlined below)
class FeedImport {
/* New Lines */
protected static $_instance = NULL;
public static function instance() {
if ( is_null( self::$_instance ) ) {
self::$_instance = new self();
}
return self::$_instance;
}
/* End New Lines */
public function __construct() {
}
// Read shortcode params
public static function shortcodeExecute($atts = '' , $content = '' ){
if(!class_exists('ParseJSON')) {
require_once plugin_dir_path( __FILE__ ) . 'class-parse-json.php';
}
// Get feed data
$response = wp_remote_get( 'https://feedurl.com' );
if(isset($response['body']) && !empty($response['body'])) {
$feedData = $response['body'];
}
// Decode feed data
$jsonData = json_decode($feedData);
// Parse feed data
$parseJSONObject = new ParseJSON($jsonData);
// Return the data in the shortcode.
return $parseJSONObject->buildHTML();
}
}
// put the short code out of the Class
add_shortcode('myshortcodename' , array( 'FeedImport', 'shortcodeExecute'));

Get updated data from wp_insert_post

i have problem with managing advanced custom fields (i have 4 of them). I want to check if some of them are empty when i add new post. I tried something like empty($_POST['name_of_post_meta']) but it does not work.
How can i catch
function wpse120996_add_custom_field_automatically($post_id)
{
global $wpdb;
if (!wp_is_post_revision($post_id)) {
$category = get_the_category($post_id);
$category = $category[0]->name;
$link = get_permalink($post_id);
if (($_POST['post_status'] == 'publish') && ($_POST['original_post_status'] != 'publish')) { // new post
$lector = get_post_meta($post_id, 'lektor_pl', true);
$subs_pl = get_post_meta($post_id, 'napisy_pl', true);
$orginal = get_post_meta($post_id, 'wersja_eng', true);
$subs_eng = get_post_meta($post_id, 'subs_eng', true);
if (empty($_POST['lektor_pl'])) {
$lector = 0;
}
if (empty($_POST['napisy_pl'])) {
$subs_pl = 0;
}
if (empty($_POST['wersja_eng'])) {
$orginal = 0;
}
if (empty($_POST['subs_eng'])) {
$subs_eng = 0;
}
if (!empty($_POST['lektor_pl'])) {
$lector = 1;
}
if (!empty($_POST['napisy_pl'])) {
$subs_pl = 1;
}
if (!empty($_POST['wersja_eng'])) {
$orginal = 1;
}
if (!empty($_POST['subs_eng'])) {
$subs_eng = 1;
}
$sql = $wpdb->prepare("INSERT INTO `wp_cron_notification` (`id`, `post_id`, `subb_pl` , `lector`, `subb_eng`, `orginal`,`link`, `category`) values (NULL, %s, %s, %s, %s, %s, %s, %s)", $post_id, $subs_pl, $lector, $subs_eng, $orginal, $link, $category);
$wpdb->query($sql) or die("ERROR #3");
}
}
}
add_action('wp_insert_post', 'wpse120996_add_custom_field_automatically', 1);
Thanks in advance for any help.
You can make use here of the ACF save_post function (http://www.advancedcustomfields.com/resources/acfsave_post/) which fires just after a post is saved. See more here:
If you put the following in your functions.php file you should be able to access the newly saved post and carry out code above. For example:
add_action('acf/save_post', 'post_save_update_title', 20);
function post_save_update_title($post_id){
//Your code here
}

Import multi-sized product with single SKU

I have regular Drupal Commerce setup with installed Feeds, Feeds Tamper and Commerce Feeds modules.
Here is tiny piece of the CSV file I'm trying to import:
SKU,Title,Price,Sizes,Model
JKR122/1,Red T-Shirt,44,"42,44,46",JKR122
JKR122/2,Blue T-Shirt,44,"42,44,46",JKR122
Is it possible using Feeds Tamper, to explode "Sizes" column and import each as separate product. Probably it will be needed to append exploded size to SKU.
I'm no pro in Excel, so if it is possible to easily reformat this huge CSV file, please tell me how.
As problem had to be solved today, I wrote PHP-script which reformats my CSV:
I'll leave question opened, in case anuone knows if this can be done by "Drupal-way".
<?php
define('ATTR_SIZE', 'Sizes');
define('ATTR_SKU', 'SKU');
define('IMPORT_FILE', 'import_file.csv');
define('EXPORT_FILE', 'export_file.csv');
define('CSV_DELIMITER', ',');
// Open csv
if(!file_exists(IMPORT_FILE) || !is_readable(IMPORT_FILE))
die('Check file');
$header = NULL;
$all_rows = array();
if (($handle = fopen(IMPORT_FILE, 'r')) !== FALSE) {
while (($row = fgetcsv($handle, 1000, CSV_DELIMITER)) !== FALSE) {
if (!$header)
$header = $row;
else
$all_rows[] = array_combine($header, $row);
}
fclose($handle);
}
// Process csv
$new_rows = array();
foreach ($all_rows as $key => $row) {
if (!empty($row[ATTR_SIZE])) {
$original_row = $row;
$sizes = explode(',', $row[ATTR_SIZE]);
foreach ($sizes as $size) {
$trimmed_size = trim($size);
if (!empty($trimmed_size)) {
$row = $original_row;
$row[ATTR_SIZE] = $trimmed_size; // Save size
$row[ATTR_SKU] = $row[ATTR_SKU] . '/' . $trimmed_size; // Modify SKU
$new_rows[] = $row; // Add new row
}
}
}
else {
$new_rows[] = $row;
}
}
// Save csv
$header = NULL;
$handle = fopen(EXPORT_FILE, 'w');
foreach ($new_rows as $fields) {
if (!$header) {
fputcsv($handle, array_keys($fields));
$header = TRUE;
}
fputcsv($handle, $fields);
}
fclose($handle);

Drupal and netForum: Creating a User

I am trying to create a user in netForum from a Drupal Webform.
Using a webform hook, I am calling two functions to take a users email address and first and last name, and create a netforum account when a user submits basic webforms.
However, the form times out when I hit submit, and the watchdog error from Netforum is 'could not fetch http headers'. Have I done something wrong in my implementation? I keep getting a timeout.
http://wiki.avectra.com/XWeb:WEBWebUserCreate
function inclind_form_webform_submission_insert($node, $submission) {
// find the email address in the form
$form_fields = $node->webform['components'];
foreach ($form_fields as $key => $value) {
$arguments = array();
$response = '';
if ($value['type'] == 'email') {
$arguments = array(
'emailToMatch' => $submission->data[$key]['value'][0]
);
$response = netforum_xweb_request('WEBWebUserFindUsersByEmail', $arguments, NULL);
if (!isset($response) || $response->{#attributes}['recordResult'] == 0) {
inclind_form_create_netforum_user($form_fields, $submission);
}
}
}
return;
}
/*
* Create a user in netForum based on form data
*
* #param $form_fields
* The form structure passed in from inclind_form_webform_submission_insert
* #param $submission
* The form data passed in from inclind_form_webform_submission_insert
*/
function inclind_form_create_netforum_user($form_fields, $submission) {
$arguments = array();
$arguments['oWebUser']['Individual'] = array();
$arguments['oWebUser']['Email'] = array();
$arguments['oWebUser']['Customer'] = array();
$arguments['oWebUser']['Business_Address'] = array();
$arguments['oWebUser']['Business_Phone'] = array();
$arguments['oWebUser']['Business_Phone_XRef'] = array();
$arguments['oWebUser']['Business_Fax'] = array();
$arguments['oWebUser']['Business_Fax_XRef'] = array();
foreach ($form_fields as $key => $value) {
if ($value['form_key'] == 'ind_first_name') {
$arguments['oWebUser']['Individual']['ind_first_name'] = $submission->data[$key]['value'][0];
}
if ($value['form_key'] == 'ind_last_name') {
$arguments['oWebUser']['Individual']['ind_last_name'] = $submission->data[$key]['value'][0];
}
if (strlen($arguments['oWebUser']['Individual']['ind_first_name']) && strlen($arguments['oWebUser']['Individual']['ind_last_name'])) {
$arguments['oWebUser']['Individual']['ind_full_name'] = $arguments['oWebUser']['Individual']['ind_first_name'] . ' ' . $arguments['oWebUser']['Individual']['ind_last_name'];
}
if ($value['form_key'] == 'eml_address') {
$arguments['oWebUser']['Email']['eml_address'] = $submission->data[$key]['value'][0];
$arguments['oWebUser']['Customer']['cst_web_login'] = $submission->data[$key]['value'][0];
$arguments['oWebUser']['Customer']['cst_new_password'] = user_password(20);
$arguments['oWebUser']['Customer']['cst_new_password_confirm'] = $arguments['oWebUser']['Customer']['cst_new_password'];
}
if ($value['form_key'] == 'adr_post_code') {
$arguments['oWebUser']['Business_Address']['adr_post_code'] = $submission->data[$key]['value'][0];
}
}
if (!isset($arguments['oWebUser']['Business_Address']['adr_city'])) {
$arguments['oWebUser']['Business_Address']['adr_city'] = 'Not Given';
}
if (!isset($arguments['oWebUser']['Business_Address']['adr_state'])) {
$arguments['oWebUser']['Business_Address']['adr_state'] = 'NA';
}
if (!isset($arguments['oWebUser']['Business_Address']['adr_post_code'])) {
$arguments['oWebUser']['Business_Address']['adr_post_code'] = '00000';
}
if (!isset($arguments['oWebUser']['Business_Address']['adr_country'])) {
$arguments['oWebUser']['Business_Address']['adr_country'] = 'Not Given';
}
if (!isset($arguments['oWebUser']['Business_Phone']['phn_number'])) {
$arguments['oWebUser']['Business_Phone']['phn_number'] = '000-000-0000';
}
if (!isset($arguments['oWebUser']['Business_Phone_XRef']['cph_extension'])) {
$arguments['oWebUser']['Business_Phone_XRef']['cph_extension'] = '000';
}
if (!isset($arguments['oWebUser']['Business_Fax']['fax_number'])) {
$arguments['oWebUser']['Business_Fax']['fax_number'] = '000-000-0000';
}
$response = netforum_xweb_request('WEBWebUserCreate', $arguments, '1 min');
watchdog('netforum', 'netforum user #user created', array('#user' => $arguments['oWebUser']['Email']['eml_address']), WATCHDOG_NOTICE);
}
Solved: http://drupal.org/node/866534

wordpress wp_list_categories problem

I need to make something like wp_list_categories that shows categories that are empty but only if they have children categories that have posts in them. Anyone have any ideas?
Thanks
You can probably do this with a Walker, but I tried it the old-fashioned way.
$categories = get_categories();
// First index all categories by parent id, for easy lookup later
$cats_by_parent = array();
foreach ($categories as $cat) {
$parent_id = $cat->category_parent;
if (!array_key_exists($parent_id, $cats_by_parent)) {
$cats_by_parent[$parent_id] = array();
}
$cats_by_parent[$parent_id][] = $cat;
}
// Then build a hierarchical tree
$cat_tree = array();
function add_cats_to_bag(&$child_bag, &$children)
{
global $cats_by_parent;
foreach ($children as $child_cat) {
$child_id = $child_cat->cat_ID;
if (array_key_exists($child_id, $cats_by_parent)) {
$child_cat->children = array();
add_cats_to_bag($child_cat->children, $cats_by_parent[$child_id]);
}
$child_bag[$child_id] = $child_cat;
}
}
add_cats_to_bag($cat_tree, $cats_by_parent[0]);
// With this real tree, this recursive function can check for the cats you need
function has_children_with_posts(&$children)
{
$has_child_with_posts = false;
foreach ($children as $child_cat) {
$has_grandchildren_with_posts = false;
if (isset($child_cat->children)) {
// Here is our recursive call so we don't miss any subcats
if (has_children_with_posts($child_cat->children)) {
$has_grandchildren_with_posts = true;
}
}
if (0 < intval($child_cat->category_count)) {
$has_child_with_posts = true;
} else if ($has_grandchildren_with_posts) {
// This is a category that has no posts, but does have children that do
$child_cat->is_empty_with_children = true;
var_dump($child_cat->name);
}
}
return $has_child_with_posts;
}
has_children_with_posts($cat_tree);

Resources