-
AuthorPosts
-
July 12, 2015 at 8:48 pm #472077
Hi, I am working on creating a script to import a list of portfolio and i am close to end the work… Only part I hardly get is how I can get and set portfolio category.
Do you think you could find me thoses 2 very little bit of code :
How to get the list of category a post is in?
How to set the category for a portfolio?Thanks in advance and gratz for this very nice theme and support
July 12, 2015 at 9:30 pm #472083Hi lepetitweb!
portfolio is a custom post type, so queries are based
<?php if ( get_query_var('paged') ) $paged = get_query_var('paged'); if ( get_query_var('page') ) $paged = get_query_var('page'); $query = new WP_Query( array( 'post_type' => 'books', 'paged' => $paged ) ); if ( $query->have_posts() ) : ?> <?php while ( $query->have_posts() ) : $query->the_post(); ?> <div class="entry"> <h2 class="title"><?php the_title(); ?></h2> <?php the_content(); ?> </div> <?php endwhile; wp_reset_postdata(); ?> <!-- show pagination here --> <?php else : ?> <!-- show 404 error here --> <?php endif; ?>
Now regarding the taxonomy, that is a way to get them:
<?php //list terms in a given taxonomy (useful as a widget for twentyten) $taxonomy = 'termcat'; $tax_terms = get_terms($taxonomy); ?> <ul> <?php foreach ($tax_terms as $tax_term) { echo '<li>' . '<a href="' . esc_attr(get_term_link($tax_term, $taxonomy)) . '" title="' . sprintf( __( "View all posts in %s" ), $tax_term->name ) . '" ' . '>' . $tax_term->name.'</a></li>'; } ?> </ul>
More informations how you want to use them, it might help!
And ofc, thx a lot for your kind words!
Regards,
Basilis- This reply was modified 9 years, 5 months ago by Basilis.
July 12, 2015 at 10:12 pm #472095Thanks a lot for thoses 2 codes, it’s very helpfull !!!
The 1st code will help me with search result page i’ll have to create and the 2nd code might help me find the right documentation to get the categories of a specific post
Thing I would miss is a way to add some categorie to a portfolio using php. To explain more, I can create portfolio page, add feature image, add texts, add tags and even add the wpml translation to that portfolio. The thing i still not get is how the link works beetween a taxonomy (categories) and a post (portfolio)… So how can I get the specific categories of a specific portfolio and how can I set specifics categories for a specific post…
Something like get_post_term( $id_post) and set_post_term ($id_post, $terms)….. Of course, this is just an exemple to clarify my need but it’s what i need…
Once again thanks a lot for this amazing support and theme, you guys rock
July 12, 2015 at 10:35 pm #472101Just wanna say that your codes helped me figure how to do it, so thanks a bunch
I was looking for thoses 2 codes :
<?php wp_get_object_terms( $object_ids, $taxonomies, $args ); ?>
<?php wp_set_object_terms( $object_id, $terms, $taxonomy, $append ); ?>I didnt know how it was called but with you pointing me about “terms”, i found it. Thanks a bunch again for the very fast and helpful response. You can flag the topic with completed and fixed, thanks
- This reply was modified 9 years, 5 months ago by lepetitweb.
July 13, 2015 at 11:23 am #472266I got almost everything working perfectly, thx to your code help, except that i have a little bug.
To make it short, I have a portfolio item that i use like a template to grab all the content and just replace some {{DATA}} in the text content to create my portfolio from my csv list. This part is working fine and at the end i have my portfolio created with tags, categories, content, title, etc.
When i check this new portfolio right away the visual is a little different then it should be (I have featured image at top, tags just over footer and some issue with css). Then if i just go edit the portfolio, dont change anything but click the update button, if I return check the portfolio, now it show perfectly…
So digging in a little more made me found that this is related to post meta. I tryed to simply copy the meta from my template portfolio but if i pick all fields i see warning appears, If i dont pick the _avia_builder_shortcode_tree and _aviaLayoutBuilderCleanData I end up with empty portfolio…
So my question is this one… Is there a function i could call to update the portfolio to force correct meta creation??
Since you helped me on this job, i’ll post my code when i am done with coding it
Thanks in advance
July 13, 2015 at 2:08 pm #472433here is the basis for my import portfolio script from a csv… Still needing to figure out what’s wrong from post_meta as explained in my last message
<?php session_start(); error_reporting(E_ALL-E_NOTICE); ini_set('display_errors', '1'); ini_set("memory_limit","500M"); ini_set('max_execution_time',500); require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php'); global $wpdb; function csv_split($line,$delim=';',$removeQuotes=false) { $fields = array(); $fldCount = 0; $inQuotes = false; for ($i = 0; $i < strlen($line); $i++) { if (!isset($fields[$fldCount])) $fields[$fldCount] = ""; $tmp = substr($line,$i,strlen($delim)); if ($tmp === $delim && !$inQuotes) { $fldCount++; $i += strlen($delim)-1; } else if ($fields[$fldCount] == "" && $line[$i] == '"' && !$inQuotes) { if (!$removeQuotes) $fields[$fldCount] .= $line[$i]; $inQuotes = true; } else if ($line[$i] == '"') { if ($line[$i+1] == '"') { $i++; $fields[$fldCount] .= $line[$i]; } else { if (!$removeQuotes) $fields[$fldCount] .= $line[$i]; $inQuotes = false; } } else { $fields[$fldCount] .= $line[$i]; } } return $fields; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Document sans titre</title> </head> <body> <?php ////////////////////////////////////////// // get detail from an existing portfolio... works like a template... ////////////////////////////////////////// $page_id = 10534; // specific Page's id from your site, which you can find by mousing over the link to edit that Page on the Manage Pages admin page. The id will be embedded in the query string of the URL, e.g. page.php?action=edit&post=123. $page_data = get_page( $page_id ); echo "<pre>"; print_r($page_data); echo "</pre>"; $page_post_tags = wp_get_post_tags($page_id); echo "<pre>"; print_r($page_post_tags); echo "</pre>"; $meta_values = get_post_meta( $page_id ); echo "<pre>"; print_r($meta_values); echo "</pre>"; //echo apply_filters('the_content', $page_data->post_content); // echo the content and retain WordPress filters such as paragraph tags. // get the featured image //$limage = wp_get_attachment_image_src( get_post_thumbnail_id( $page_id ), 'single-post-thumbnail' ); //echo "<pre>"; print_r($limage); echo "</pre>"; // Get all the portfolios categories list $args = array( 'orderby' => 'name', 'order' => 'ASC', 'hide_empty' => false, ); $tax_terms = get_terms('portfolio_entries', $args); //echo "<h2>Terms:</h2> <pre>"; print_r($tax_terms); echo "</pre>"; // get the categories for a specific portfolio item //$product_terms = wp_get_object_terms( $page_id, 'portfolio_entries' ); //echo "<pre>"; print_r($product_terms); echo "</pre>"; ////////////////////////////////////////// // Read CSV file and put it in a array of lines column ///////////////////////////////////////// $datas = array(); $contenu = file("capsules.csv"); $the_limite = 2; //Number of line read max... if higher then number of line in file it will just get all line $liste_full = array(); if (is_array($contenu)){ $x = 0; $compteur = 0; foreach ($contenu as $line){ if ($x > 0 && $x < $the_limite + 1){ // Traitement pour problème d'accent avec excel $line = trim(iconv("Windows-1252", "UTF-8", " ".$line." ")); // Découpage de la ligne en champs $data = csv_split($line,';',true); // Si c'est pas une ligne vide on l'ajoute a notre tableau if (!empty($data[0])){ // $liste_full[] = strtolower($data[0]); $liste_full[] = $data; } } ++$x; } echo "<p>Liste full de ".$x. " items</p>"; } // List of detail lines from csv file // We have 1 line per language and i reverse the array to get the main language first for each portfolio $liste_full = array_reverse($liste_full); echo "<pre>"; print_r($liste_full); echo "</pre>"; // LOOP all item in the list to add portfolios pages $trid = 0; foreach($liste_full as $line){ // Filling some variables $tags = $line[8]; // List of tags for the portfolios $image_url = "images_capsules/".$line[2]; // URL of the picture for featured image $category_letter = strtoupper(substr($line[0], 0, 1)); $array_category_name = array("VIDEO", $category_letter); // List of exact category names to add to this portfolio case sensitive // Replacement for the Template tags from data from csv $content = $page_data->post_content; $content = str_replace("{{TITLE}}", $line[0], $content ); $content = str_replace("{{LINK_IMAGE}}", $line[2], $content ); $content = str_replace("{{LINK_CAPSULE}}", $line[4], $content ); $content = str_replace("{{LINK_FILE}}", $line[5], $content ); $content = str_replace("{{DESCRIPTION}}", $line[7], $content ); // filling post basic data $page = array(); $page['post_type'] = 'portfolio'; $page['post_title'] = $line[0]; $page['post_content'] = $content; $page['post_excerpt'] = $line[3]; $page['post_parent'] = 0; $page['post_author'] = 1; // $user_ID; $page['post_status'] = 'publish'; //Add page $pageid = wp_insert_post ($page); if ($pageid == 0) { // Add Page Failed echo "<h2>Error while creating the page with title : ".$line[0]."</h2>"; } // if main language post get the TRID for the WPML link if ($line[6] == "FR"){ $results = $wpdb->get_results( 'SELECT * FROM wpdb_icl_translations where element_id = '.$pageid, OBJECT ); foreach ($results as $row){ $trid = $row->trid; } // if second lang, we update the date in icl_translations } else { $wpdb->query( 'UPDATE wpdb_icl_translations SET source_language_code = "fr", language_code = "en", trid = '.$trid.' where element_id = '.$pageid.' AND element_type="post_portfolio"' ); } // apply tags to the portfolio wp_set_post_tags( $pageid, $tags, false ); // tags separé par , last item true = add false = replace //Set featured image if ($line[6] == "FR"){ // Insert the image only for main language since image will be same for both language $upload_dir = wp_upload_dir(); $image_data = file_get_contents($image_url); $filename = basename($image_url); if(wp_mkdir_p($upload_dir['path'])){ $file = $upload_dir['path'] . '/' . $filename; } else { $file = $upload_dir['basedir'] . '/' . $filename; } file_put_contents($file, $image_data); $wp_filetype = wp_check_filetype($filename, null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $file, $pageid ); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); } wp_update_attachment_metadata( $attach_id, $attach_data ); set_post_thumbnail( $pageid, $attach_id ); // Set portfolio categories $list_cat = array(); foreach ($tax_terms as $taxo){ if (in_array($taxo->name, $array_category_name)){ $list_cat[] = $taxo->term_id; } } $list_cat = array_map( 'intval', $list_cat ); $list_cat = array_unique( $list_cat ); $term_taxonomy_ids = wp_set_object_terms( $pageid, $list_cat, 'portfolio_entries', true ); if ( is_wp_error( $term_taxonomy_ids ) ) { echo "<h2>There was an error somewhere and the categories couldn't be set.</h2>"; } /* foreach ($meta_values as $key => $value) { if ($key == "_aviaLayoutBuilderCleanData") { $value[0] = $content; } if ( ! add_post_meta( $page_id, $key, $value[0], true ) ) { update_post_meta ( $page_id, $key, $value[0] ); } } */ } ?> </body> </html>
July 13, 2015 at 7:25 pm #472627any Idea about how to generate the post_meta like if i clicked update on the admin ? There must be a function i can call to generate the right value… It’s the only thing who’s not working in my whole import script… Wish you can help me with this.
Thanks in advance
July 14, 2015 at 5:05 pm #473312No Ideas?
July 15, 2015 at 10:18 pm #474002someone could have a look at this thread please? 1st feedback was really fast but need a little help to end my script
July 17, 2015 at 1:05 pm #474893Hi!
Next replies would also be fast, but every time you do post something, the ticket goes to the end of the list, so I could not track it! :-)
While we an point in the correct direction with our reply, I can not debug the hole code, to be sure what the problem might be.
I can keep assisting with the changes, but I need to know an exact problem you deal with, so I can help you further.
if that is not possible through your side thenYou can contact one of our Customization Contractors, who will help you out with the process.
http://kriesi.at/contact/customizationLet us know if we could do anything else, regarding our theme
Best regards,
BasilisJuly 17, 2015 at 4:59 pm #475057thx for the answer.
I posted my whole code only for user reference later. The exact problem i deal with is the following :
When i insert portfolio everything works fine. I have post, featured image, category, tags working. But i think i miss some meta post data cause when i display the portfolio it doesnt looks right like other post (featured image at top, tag showing at footer and css messed up). After that if i just go to the portfolio page and hit save button without any modification, it display correctly because the wordpress UI must assign the right meta post.
So the exact instruction i need who be how to call a function that would generate the appropriate meta post data because if i just try to set them exactly like my template portfolio it’s doesnt work good either
July 17, 2015 at 7:11 pm #475127Hey!
Please do look here:
enfold/includes/admin/register-portfolio.phpwhere we do register the portfolio class and the helpers for the portfolio.
let me know if that helps you out
Regards,
Basilis -
AuthorPosts
- The topic ‘Add portfolio by php script’ is closed to new replies.