PHP Script for Wordpress: Creating CPTs with CSV - php

i just started learning php. I tried to create a script, which goes through an CSV and creates a CPT for each row in my Wordpress-System. Each column should fill the title/ACF-Fields.
Code:
$csv_file_path = 'link-to-csv';
function create_wp_cpt_from_csv() {
global $csv_file_path;
if (($handle = fopen($csv_file_path, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
$post = array(
'post_title' => $data[0],
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'sorten'
);
$post_id = wp_insert_post($post);
update_field('acf_1', $data[1], $post_id);
update_field('acf_2', $data[2], $post_id);
}
fclose($handle);
}
}
add_action('init', 'create_link_to_import_csv');
function create_link_to_import_csv() {
add_menu_page( 'Import CSV', 'Import CSV', 'manage_options', 'import_csv', 'import_csv_function');
}
function import_csv_function(){
create_wp_cpt_from_csv();
}
I changed the link of the csv.
I implemented this code in my functions.php. Unfortunately, whenever i click on the "Import CSV" button, nothing happens.

Related

wordpress acf repeater mapping in custom field post not working

After a long search on the net, my code didn't come up with what I wanted.
I with wordpress and acf , the purpose of the function is to return a mapped array from a costumed post type.
I created and saved the costum post type named 'myCpt' to which I linked it with acf type fields: (text and repeater)
I was able to retrieve the text value but I can't get the repeater values.... Thanks for seeing the var_dump() image
Your help will be very valuable to me.
class myClass
{
function __construct()
{
var_dump($this->get_all());
}
function get_all()
{
$args = array(
'post_type' => 'myCpt',
'posts_per_page' => 999,
'post_status' => 'publish'
);
$myCpt = get_posts($args);
$myCpt_mapped = array_map(function ($myCpt) {
$id = $myCpt->ID;
return array(
'id' => $id,
'title' => get_field('maintitle', $id, false),
'subtitle' => get_field('subtitle', $id, false),
// 'services' => services repeater
'repField' => array(
'name' => get_sub_field('name', $id, false),
'img' => get_sub_field('img', $id, false)
)
);
}, $myCpt);
return array(
'myCpt' => $myCpt_mapped
);
}
}
global $myClass;
$myClass = new $myClass();}
resultat:
var_dump()

Custom Wordpress shortcode not displaying the form on the front end

I have duplicated an existing plugin in WordPress to add an additional (identical) form for a new post type that I have created. I have renamed the shortcode in the new plugin so that it does not display the original form, yet it is not being displayed when I add the shortcode to the block editor.
I tried looking through functions.php or everywhere else to see if this shortcode is being registered anywhere else to no avail. If it's identical in code to the original plugin aside from its name, shouldn't it be displaying with its new name? Here's the code snippet of my shortcode.
<?php
function get_wpsisac_submission_form( $atts, $content = null ){
$view_file = WPSISAC_VERSION_DIR . '/templates/form.php';
extract(
shortcode_atts(
array(
"limit" => '-1'
), $atts));
ob_start();
if (isset($_POST['submit-form'])) {
global $wpdb;
$artist = $_POST['artist_name'];
$data = array(
'post_title'=> addslashes($_POST['post_title']),
'post_type'=>'pbrartxth',
'post_content'=>'',
'post_status' => 'draft',
'post_category' => array(14),
'meta_input' => array(
'artist_name' => addslashes($_POST['artist_name']),
'art_type' => $_POST['art_type'],
'art_year' => date('Y'),
'art_description' => addslashes($_POST['art_description']),
'art_video_url' => $_POST['video_url'],
'artist_age' => $_POST['artist_age'],
'artist_address' => $_POST['artist_address_one'],
'artist_address_two' => $_POST['artist_address_two'],
'artist_city' => $_POST['artist_city'],
'artist_state' => $_POST['artist_state'],
'artist_zip' => $_POST['artist_zip'],
'artist_email' => $_POST['artist_email'],
'artist_phone' => $_POST['artist_phone'],
'artist_website' => $_POST['artist_website'],
'artist_web' => $_POST['artist_website'],
'artist_instagram_handle' => $_POST['artist_instagram_handle'],
// 'artist_twitter_handle' => $_POST['artist_twitter_handle'],
)
);
$post_id = wp_insert_post($data);
if (!empty($_FILES['gif_upload_field']['name'])) {
$uploadedfile = $_FILES['gif_upload_field'];
} else if (!empty($_FILES['jpg_upload_field']['name'])) {
$uploadedfile = $_FILES['jpg_upload_field'];
};
$attachment_id = upload_user_file( $uploadedfile, $post_id );
update_field('_thumbnail_id', $attachment_id, $post_id);
echo "<div><p>Thank you for your submission $artist! We will review the information you have provided us.</p></div>";
// print_r($_POST);
// echo 'Post ID: ' . $post_id;
// echo 'GIF File: ' . print_r($uploadedfile);
// echo 'JPG File: ' . print_r($uploadedfile);
// echo'</pre>';
// exit;
}
include( $view_file );
return ob_get_clean();
};
add_shortcode('th-load-form-submission','get_wpsisac_submission_form');
Please let me know if there is something I'm missing. This is the only instance I found that made reference to the shortcode name.

Save CSV Export to Server

I have the code below which triggers when a button is pressed in the WordPress admin panel. This opens a csv file called 'ss-stock-export.csv'.
How can I save this file to my server in my uploads directory at wp-content/uploads/exports/? I tried to use file_put_contents but that doesn't seem to be working right. The CSV file appears in the right spot but it is blank. Possibly something wrong with my $output?
<?php
function generate_stock_report_csv() {
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
// set file name with current date
header('Content-Disposition: attachment; filename=ss-stock-export.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// set the column headers for the csv
$headings = array( 'sku', 'qty', 'is_in_stock' );
// output the column headings
fputcsv($output, $headings );
// get all simple products where stock is managed
// get all product variations where stock is managed
$args = array(
'post_type' => 'product_variation',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => '_stock',
'value' => array('', false, null),
'compare' => 'NOT IN'
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$product = new WC_Product_Variation( $loop->post->ID );
$ss_sku = get_post_meta( $product->variation_id, 'ss_sku', true);
$stock = $product->stock;
settype($stock, "integer");
if ($stock > 0){ $stock_status = 1;} else {$stock_status = 0;}
$row = array( $ss_sku , $product->stock, $stock_status );
fputcsv($output, $row);
endwhile;
$filename = "ss-stock-export.csv"; // Trying to save file in server
file_put_contents(ABSPATH . "wp-content/uploads/exports/" . $filename, $output);
} ?>
You can use the ABSPATH constant defined in wp-config.php to pass an absolute path to file_put_contents. That way it doesn't matter where you're running the script from.
file_put_contents(ABSPATH . "wp-content/uploads/exports/" . $filename, $output);
This did the trick
$csv = "sku,qty,is_in_stock \n";//Column headers
$args = array(
'post_type' => 'product_variation',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => '_stock',
'value' => array('', false, null),
'compare' => 'NOT IN'
)
)
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$product = new WC_Product_Variation( $loop->post->ID );
$ss_sku = get_post_meta( $product->variation_id, 'ss_sku', true);
$stock = $product->stock;
settype($stock, "integer");
if ($stock > 0){ $stock_status = 1;} else {$stock_status = 0;}
$row = array( $ss_sku , $product->stock, $stock_status );
$row_array= array($row);
foreach ($row_array as $record){
$csv.= $record[0].','.$record[1].','.$record[2]."\n"; //Append data to csv
}
endwhile;
$csv_handler = fopen ('ss-stock-export.csv','w');
fwrite ($csv_handler,$csv);
fclose ($csv_handler);
file_put_contents(ABSPATH . "wp-content/uploads/exports/ss-stock-export.csv", $csv);
}

Adding tag input in post form

So, I have following form in my plugin for post upload (wordpress):
if(empty($_POST['post_id'])){
$post = array(
'post_content' => 'Dummy Content',
'post_title' => 'Dummy Title',
'post_status' => 'inherit',
'post_type' => 'post'
);
$post_id = wp_insert_post( $post, true );
}else{
$post_id = $_POST['post_id'];
}
$upload_dir = wp_upload_dir();
$files = $_FILES['files'];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$filename = rand() . '' . $files['name'][$key];
$file = array(
//Here goes other irrelevant code
);
$upload_overrides = array( 'test_form' => false );
$image_path[] = array(
'image_path' => $upload_dir['url'] . '/' . $filename,
'meta_key' => 'upload_image',
'meta_value' => $upload_dir['url'] . '/' . $filename,
'post_id' => $post_id
);
add_post_meta($post_id, 'upload_image', $upload_dir['url'] . '/' . $filename );
}
}
echo json_encode($image_path);
exit;
Above function adds an image as a post with dummy contents such as title/description etc.
Now, if I want to update the content, then I can do so by following:
global $wpdb;
$tags = $_POST['rh_tags'];
if(!empty($_POST['post_id'])){
$data = array(
'post_title' => $_POST['title'],
'post_content' => $_POST['content'],
'tags_input' => $tags,
'post_status' => 'publish'
);
$where = array('ID' => $_POST['post_id']);
$update = $wpdb->update($wpdb->prefix . 'posts' , $data, $where, $format = null, $where_format = null );
}else{
$post = array(
'post_title' => $_POST['title'],
'post_content' => $_POST['content'],
'post_status' => 'publish',
'tags_input' => $tags,
'post_type' => 'post'
);
wp_insert_post($post);
}
echo 'success';
exit;
Here I added 'tags_input' => $tags, to add a post tag.
Here is current situation:
1. No image selected: in the input field (a form with simple input field with title, description and tag), if I add something to the tag input while there is no image selected, then the post is created properly with the tag.
2. Image selected: if an image is selected, then with the tag input, it does not create the post at all.
I tried to add 'tags_input' => $tags, in the very first function, but that did not work either.
Can someone point out what change I need to make in my first function?
Suggest you add some var_dump statements if this is still a problem. When followed by an exit; statement, this will immediately show the data in the object.
I'd want to look at the state of the data within each if/then statement and the expected data in each function.
Of course, the data before and after your image is created/uploaded. Then I would expect the problem to become visible.
So generally, I'd do the following to debug the issue.
At various places put the following debugging code and you may also add the different critical variables using a comma separator in the var_dump function:
var_dump($_POST);
exit;
You also should consider using better variable names because the code
is more confusing to debug than it needs to be. The variable names are
not consistent even within a single if/then loop for example in the
second function you mention $data and then $post.

Add html/PHP pages on plugin activation (Wordpress)

Well am creating my first wordpress plugin, which should create a page (relatively large) on activation.
Currently i can create a file using :
$_p['post_title'] = $the_page_title;
$_p['post_content'] = '<h1>PAGE CONTENT</h1>';
$_p['post_status'] = 'publish';
$_p['post_type'] = 'page';
$_p['comment_status'] = 'closed';
$_p['ping_status'] = 'closed';
$_p['post_category'] = array(1); // the default 'Uncatrgorised'
// Insert the post into the database
$the_page_id = wp_insert_post( $_p );
The problem is, I cant put all the content of the file(which is large) as string to 'post_content' index. I want to know if there is a way, where i can simply either:
'post_content' => link to the file in my plugin directory
'post_content' => call a function which will return html content as string :( [worst case]
OR, Some more simpler way to achieve the objective.
Please help me.
Well, what i did to solve the problem is:
//**SECTION : 1**
function user_login_foo() {
return get_login_form(); // get_login_form() function will return the html template i want to display.
}
add_shortcode('user_login', 'user_login_foo'); // created a shortcode
**// SECTION: 2**
function get_login_form()
{
ob_start(); ?>
<h3><?php __('Login'); ?></h3>
<form action="" method="post">
<fieldset>
// the login form comes here
</fieldset>
</form>
<?php
return ob_get_clean();
}
function validate_login_user() {
// the login validation logic comes here
}
add_action('init', 'validate_login_user');
SECTION 1: registered a shortcode that will call a function [say,foo1()] and return the value.
The function foo1() calls another a function [say foo2()] which returns a clean html form in response to the call (when the shortcode is called).
SECTION 2: In this section I defined the function foo2(), within which the html form [login form] is defined and returned to foo1() [where it is displayed].
Then i created an action [ add_action('init', 'validate_login_user'); ] which will call the function validate_login_user() on initialization, inside this function i checked for isset(METHOD[username]) and isset(METHOD[password]) and then do respective logic.
Like this i created multiple [shortcodes] for each of the pages I wanted to create at the time of activation,
Then :
**step 1:** register_activation_hook(__FILE__,'activation_plugin');
**step 2:** activation_plugin(){
'390' => [ // '390' is page id
'post_title' => 'Page title say login',
'post_content' => "[user_login]",
'post_status' => 'publish',
'post_type' => 'page',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_category' => array(1)
],
'391' => [
'post_title' => 'page title 2',
'post_content' => "[short_code2]",
'post_status' => 'publish',
'post_type' => 'page',
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_category' => array(1)
],
// like this add multiple shortcodes
}
// this foreach will create all the pages
foreach ($_ as $key => $value) {
$the_page_title = $value['post_title'];
$the_page_name = $value['post_title'];
// the menu entry...
delete_option($value['post_title']);
add_option($value['post_title'], $the_page_title, '', 'yes');
// the slug...
delete_option($value['post_title']);
add_option($value['post_title'], $the_page_name, '', 'yes');
// the id...
delete_option($key);
add_option($key, '0', '', 'yes');
$the_page = get_page_by_title( $the_page_title );
if ( ! $the_page ) {
$the_page_id = wp_insert_post( $value );
}
else {
$the_page_id = $the_page->ID;
$the_page->post_status = 'publish';
$the_page_id = wp_update_post( $the_page );
}
delete_option( $key );
add_option( $key, $the_page_id );
}
Create Page On Plugin activation with content
$page_content= 'Content of page';
$demo_page = array(
'comment_status' => 'closed',
'ping_status' => 'closed' ,
'post_author' => 1,
'post_content' => $page_content,
'post_date' => date('Y-m-d H:i:s'),
'post_name' => 'page_name',//display on address bar
'post_status' => 'publish' ,
'post_title' => 'Page Display Name',
'post_type' => 'page',
);
//insert page and save the id
$demo_page_value = wp_insert_post( $demo_page, false );
//save the id in the database
update_option( 'testpage', $$demo_page_value );
You Use and Guide and read this link How to Create plugin and pages https://codex.wordpress.org/Creating_Options_Pages

Categories