I build a form that enable users to post from the frontend.
I am trying to make it pass a taxonomy as well with the wp_set_object_terms becouse I use a custom post type and a custom taxonomy.
this is my code:
if(isset ($_POST['submit_offer'])=='submit'){
$user_id = get_current_user_id();
$args=array(
'post_author' => $user_id,
'post_title' => $_POST['job_title'],
'post_content' => $_POST['post_content'],
'post_excerpt' => $_POST['job_field'],
'meta_input' => array(
'points_amount' => $_POST['post_points'],
),
'post_status' => 'publish',
'post_type' => 'job_offers',
);
// get post id
$post_id = wp_insert_post($args);
$job_tax = array ( 44 , 45 );
wp_set_object_terms( $post_id , $job_tax, 'field_of_work' );
}
and Its not working!!!!!
Also for those who have custom post type & custom taxonomy and their code is in functions.php be sure to give a low priority (20) for the function that inserts the post(s). That will do the trick!
Here is an approach for wp_insert_post() in functions.php:
function insert_db_posts() {
$thepost = wp_insert_post(array(
'post_type' => 'art',
'post_title' => 'Try hard',
));
wp_set_object_terms( $thepost, 37, 'artist');
}
add_action( 'init', 'insert_db_posts', 20 ); // this will fire very late!!!
So, finally solved it. Just needed to wrap the form in a function and add it to init. :
<? php
function job_offer_form_init() {
// form to post test
function job_offer_form() {
$user_id = get_current_user_id();
$job_field_1 = userpro_profile_data('main_occupation', $user_id);
$job_field_2 = userpro_profile_data('sub_occupation_01', $user_id);
$job_field_3 = userpro_profile_data('sub_occupation_02', $user_id);
$form ='<div class="form-container">
<form action="" method="post" role="form">
<legend>הצעת שירותים/מוצרים</legend>
<div class="form-group">
<label for="job_title">כותרת ההצעה</label></br>
<input type="text" class="form-control" name="job_title" placeholder=""></br>
<label for="post_content">תוכן ההצעה</label></br>
<textarea class="form-control" name="post_content" placeholder=""></textarea></br>
<label for="job_field">תחום ההצעה</label></br>
<select name="job_field" multiple>
<option value="'.$job_field_1.'" selected>'.$job_field_1.'</option>
<option value="'.$job_field_2.'">'.$job_field_2.'</option>
<option value="'.$job_field_3.'">'.$job_field_3.'</option>
</select></br>
<label for="post_points">עלות בנקודות</label></br>
<input type="number" class="form-control" name="post_points" placeholder=""></br>
</div>
<button type="submit" name="submit_offer" value="submit" class="btn btn-primary">הגשת הצעה</button>
</form></div>' ;
return $form;
}
add_shortcode( 'jobofferform', 'job_offer_form' );
if(isset ($_POST['submit_offer'])=='submit'){
$user_id = get_current_user_id();
$args=array(
'post_author' => $user_id,
'post_title' => $_POST['job_title'],
'post_content' => $_POST['post_content'],
'post_excerpt' => $_POST['job_field'],
/* 'tax_input' => array(
'field_of_work' => array(44, 45),
), */
'meta_input' => array(
'points_amount' => $_POST['post_points'],
// 'job_field' => $_POST['job_field'],
),
'post_status' => 'publish',
'post_type' => 'job_offers',
);
// get post id
$post_id = wp_insert_post($args);
$job_tax = array ( 48 , 49 );
$term_taxonomy_ids=wp_set_object_terms( $post_id , $job_tax, 'field-of-work' , true );
if (is_wp_error($term_taxonomy_ids )) {
$error_string= $term_taxonomy_ids -> get_error_message();
add_post_meta( $post_id, 'taxonomies-error', $error_string );
} else {
add_post_meta( $post_id, 'taxonomies-error', 'no error' );
}
}
}
add_action( 'init', 'job_offer_form_init', 0 );
?>
Related
I'm developping a front-end interface to create a certain type of post (teams with Sportspress).
For this i'm using the wp_insert_post() function in my custom plugin.
Made a really simple form :
<?php
function team_creation() {
?>
<form action="POST">
<h3>CREER VOTRE EQUIPE</h3>
<input type="text" name="post_title">
<textarea name="post_content" id="" cols="30" rows="10"></textarea>
<div id="button_container">
<input type="submit" name="button_submit" value="Sauvegarder" id='save'/>
</div>
</form>
<?php
if(isset($_POST['button_submit'])) {
if (!empty($_POST['post_title'])) {
$my_post = array(
'post_title' => $_POST['post_title'],
'post_content' => $_POST['post_content'],
'post_type' => 'team',
'post_status' => 'publish',
'post_author' => get_current_user_id(),
);
// Insert the post into the database
wp_insert_post( $my_post, true );
} else {
echo 'WTF BRO';
}
}
}
?>
I still have a "page not found" page when submitting the form. Do you know why ?
"404 not found, the page you are looking for has been moved or doesn't exist anymore"
Thanks !
Try adding these before your if ISSET line.
global $wpdb;
global $post;
So it looks like this:
<?php
global $wpdb;
global $post;
if(isset($_POST['button_submit'])) {
if (!empty($_POST['post_title'])) {
$my_post = array(
'post_title' => $_POST['post_title'],
'post_content' => $_POST['post_content'],
'post_type' => 'team',
'post_status' => 'publish',
'post_author' => get_current_user_id(),
);
// Insert the post into the database
wp_insert_post( $my_post, true );
} else {
echo 'WTF BRO';
}
}
}
?>
And if that doesn't work try adding it in a different way using this command:
$table_name = 'posts';
$wpdb->insert($table_name, $my_post, $format=NULL);
Ok it was finally a dumb error of myself... The post_type was not 'team' but 'sp_team'. I have print_r the get_post_types() to get all type of post and saw that...
Thanks all for the help and have a nice day/night :)
I have a front end form which will create two individual posts from the one form. My issue is when setting the custom taxonomy for each post, it will only input the first selection and not the full array of selections.
If I remove the [$key] from $services = $taxinput["job_listing_category"][$key];, it will then add all of the taxonomy selections from both inputs to both of the two posts.
I cant work out why I either have just a single taxonomy selection only applied to the correct individual post, or I have all taxonomy selections from both inputs added to both posts.
if($_POST){
foreach($_POST['class_name_1'] as $key =>$makepost)
{
if(strlen($makepost)>3){
$post_id = -1;
$taxinput = $_POST["tax_input"];
$services = $taxinput["job_listing_category"][$key];
$class_name_1 = $_POST['class_name_1'][$key];
$post_id = wp_insert_post(
array(
'comment_status' => 'closed',
'ping_status' => 'closed',
'post_author' => $author_id,
'post_name' => '',
'post_title' => '',
'post_status' => 'pending',
'post_type' => 'job_listing',
'post_content' => ''
)
);
wp_set_post_terms( $post_id, $services, 'job_listing_category', true);
wp_add_post_meta( $post_id, 'class_name_1', $class_name_1);
}
}
}
Here is my frontend input form:
<form action="" method="post" id="submit-class" class="job-manager-form" enctype="multipart/form-data">
<div class="class-name-edit">
<label for="class_name">Class Name:</label>
<div class="field ">
<?php
get_job_manager_template( 'form-fields/text-field.php',
array(
'key' => 'class_name_1[]',
'field' => $all_fields['class_name_1']
)
);
?>
</div>
</div>
<div class="service-category classes">
<label for="job_category">Class categories:</label>
</div>
<?php
get_job_manager_template( 'form-fields/term-checklist-field.php',
array(
'key' => 'job_category[]',
'field' => $all_fields['job_category']
)
);
?>
</div>
</div>
<div class="class-name-edit">
<label for="class_name">Class Name:</label>
<div class="field ">
<?php
get_job_manager_template( 'form-fields/text-field.php',
array(
'key' => 'class_name_1[]',
'field' => $all_fields['class_name_1']
)
);
?>
</div>
</div>
<div class="service-category classes">
<label for="job_category">Class categories:</label>
</div>
<?php
get_job_manager_template( 'form-fields/term-checklist-field.php',
array(
'key' => 'job_category[]',
'field' => $all_fields['job_category']
)
);
?>
</div>
</div>
<div class="whitebox submitform">
<input type="submit" name="submit_job" class="button" value="Submit for Admin Approval" />
</div>
</form>
I've been banging my head against the wall trying to save a custom meta box select option. I am having a hard time figuring out what I actually target to save the value, since I have multiple options in the dropdown. I try to target the select name="XXX" but still no luck. Any help would be greatly appreciated.
Here is my code to show the select option dropdown:
<?php
$accessory_product_args = [
'posts_per_page' => -1,
'tax_query' => [
'relation' => 'AND',
[
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'accessories'
],
],
'post_type' => 'product',
'orderby' => 'title',
];
$accessory_product = new WP_Query( $accessory_product_args ); ?>
<select name="_accessories_product_one" id="_accessories_product_one" class="widefat">
<?php while ( $accessory_product->have_posts() ) : $accessory_product->the_post();
$title_one = get_the_title();
$postid_one = get_the_ID(); ?>
<option value="<?=$postid_one?>" <?php selected( '_accessories_product_one[select_field_0]', $postid_one); ?>>
<?=$title_one?>
</option>
<?php endwhile; ?>
</select>
<?php
//this below is used for testing to see if i have saved the value or not:
$dropdown_option = get_option( '_accessories_product_one' ); // Array
$dropdown_value = $dropdown_option ['select_field_0']; // Option value
var_dump($dropdown_option);
var_dump($dropdown_value);
?>
This code is the saving:
<?php
if (isset($_POST['_accessories_product_one']) {
update_post_meta( $post_id, '_accessories_product_one', $_POST['_accessories_product_one']);
} ?>
Any help would be greatly appreciated.
EDIT:
I am using this within the woocommerce product screen - not Page edit or Post edit or a plugin edit screen.
Here is a more verbose paste of the full code I am using:
function custom_product_basic_load() {
add_action( 'add_meta_boxes_product' , 'custom_product_basic_add_meta_boxes_product' );
add_meta_box( 'custom_product_basic_metabox' , __( 'Product Layout' ) , 'custom_product_basic_metabox' , 'product' , 'normal' , 'high' );
add_action( 'save_post' , 'custom_product_basic_save_post' , 10 , 3 );
}
add_action( 'load-post.php' , 'custom_product_basic_load' );
add_action( 'load-post-new.php' , 'custom_product_basic_load' );
function custom_product_basic_metabox( $post ) {?>
<input type="hidden" name="product_type" value="simple" />
<?php
$accessory_product_args = [
'posts_per_page' => -1,
'tax_query' => [
'relation' => 'AND',
[
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'accessories'
],
],
'post_type' => 'product',
'orderby' => 'title',
];
$accessory_product = new WP_Query( $accessory_product_args ); ?>
<select name="_accessories_product_one" id="_accessories_product_one" class="widefat">
<?php while ( $accessory_product->have_posts() ) : $accessory_product->the_post();
$title_one = get_the_title();
$postid_one = get_the_ID(); ?>
<option value="<?=$postid_one?>" <?php selected( '_accessories_product_one[select_field_0]', $postid_one); ?>>
<?=$title_one?>
</option>
<?php endwhile; ?>
</select>
<?php
$dropdown_option = get_option( '_accessories_product_one' ); // Array
$dropdown_value = $dropdown_option ['select_field_0']; // Option value
var_dump($dropdown_option);
var_dump($dropdown_value);
?>
<?php }
function custom_product_basic_save_post( $post_id ) {
if (isset($_POST['_accessories_product_one'])) {
update_post_meta( $post_id, '_accessories_product_one', $_POST['_accessories_product_one']);
}
}
Try this. you are storing the value in post_meta. but getting from get_option. Do not use get_option to get the post meta value.
function custom_product_basic_load() {
add_action( 'add_meta_boxes_product' , 'custom_product_basic_add_meta_boxes_product' );
add_meta_box( 'custom_product_basic_metabox' , __( 'Product Layout' ) , 'custom_product_basic_metabox' , 'product' , 'normal' , 'high' );
add_action( 'save_post' , 'custom_product_basic_save_post' , 10 , 3 );
}
add_action( 'load-post.php' , 'custom_product_basic_load' );
add_action( 'load-post-new.php' , 'custom_product_basic_load' );
function custom_product_basic_metabox( $post ) {?>
<input type="hidden" name="product_type" value="simple" />
<?php
echo $productLayout = get_post_meta( $post->ID, '_accessories_product_one',true);
$accessory_product_args = [
'posts_per_page' => -1,
'tax_query' => [
'relation' => 'AND',
[
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'accessories'
],
],
'post_type' => 'product',
'orderby' => 'title',
];
$accessory_product = new WP_Query( $accessory_product_args ); ?>
<select name="_accessories_product_one" id="_accessories_product_one" class="widefat">
<?php while ( $accessory_product->have_posts() ) : $accessory_product->the_post();
$title_one = get_the_title();
$postid_one = get_the_ID(); ?>
<option value="<?=$postid_one?>" <?php selected( $productLayout, $postid_one); ?>>
<?=$title_one?>
</option>
<?php endwhile; ?>
</select>
<?php
}
function custom_product_basic_save_post( $post_id ) {
if (isset($_POST['_accessories_product_one'])) {
update_post_meta( $post_id, '_accessories_product_one', $_POST['_accessories_product_one']);
}
}
This is the base of my code. The idea is that when I click submit the form posts to the same page and runs my code inside the if statement. The problem is that when I hit submit I get a Wordpress error saying Cannot load tb-export. I have done a lot of Google searches and can not find a solution.
Edit: Here is the whole class. https://pastebin.com/i03m9a3x
Edit Again: I took the code outside of the class and simplified it and I am still getting the error. Below is the simplified code and after I submit the form I get the error Cannot load export_display.
add_action('admin_menu', 'tb_admin_menu');
function tb_admin_menu() {
add_menu_page(
'Table Builder',
'Table Builder',
'read',
'i15-table-builder',
'',
'dashicons-screenoptions',
21
);
add_submenu_page('i15-table-builder', 'Export', 'Export', 'manage_options', 'export_display', 'export_display');
}
function export_display(){
if ($_POST['submit']) {
$post_args = array(
'post_type' => $_POST['post_type'],
'post__in' => $_POST['ids']
);
$posts = get_posts($post_args);
$count = 0;
foreach ( $rtp_posts as $post ) {
$write_array[$count] = array(
'post_id' => $post->ID,
'comment_status' => $post->comment_status,
'ping_status' => $post->ping_status,
'post_author' => $post->post_author,
'post_content' => $post->post_content,
'post_excerpt' => $post->post_excerpt,
'post_name' => $post->post_name,
'post_parent' => $post->post_parent,
'post_password' => $post->post_password,
'post_status' => $post->post_status,
'post_title' => $post->post_title,
'post_type' => $post->post_type,
'to_ping' => $post->to_ping,
'menu_order' => $post->menu_order
);
$taxonomies = get_object_taxonomies($post->post_type); // returns array of taxonomy names for post type, ex array("category", "post_tag");
foreach ($taxonomies as $taxonomy) {
$post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'slugs'));
$write_array[$count]['taxonomies'][$taxonomy] = $post_terms;
}
$post_meta_infos = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->postmeta WHERE post_id=$post_id");
if (count($post_meta_infos)!=0) {
$sql_query = "INSERT INTO $wpdb->postmeta (post_id, meta_key, meta_value) ";
$countmetas = 0;
foreach ($post_meta_infos as $meta_info) {
$meta_key = $meta_info->meta_key;
if( $meta_key == '_wp_old_slug' ) continue;
$meta_value = addslashes($meta_info->meta_value);
$write_array[$count]['metas'][$countmetas]['meta_key'] = $meta_key;
$write_array[$count]['metas'][$countmetas]['meta_value'] = $meta_value;
$countmetas++;
}
}
$count++;
}
$write_array_encode = json_encode($write_array);
header('Content-disposition: attachment; filename=Table_Builder_Exported_Data.json');
header('Content-type: application/json');
echo $write_array_encode;
exit();
} else {
$template_args = array(
'post_type' => 'tb_template',
'post_status' => 'any',
'numberposts' => '-1'
);
$template_posts = get_posts($template_args);
foreach ( $template_posts as $template_post ) {
$select_templates .= '<option value="'.$template_post->ID.'">'.$template_post->post_title.'</option>';
}
echo '<form method="post" action="" enctype="multipart/form-data">';
echo '<input type="hidden" name="post_type" value="tb_template" />';
echo '<select multiple="multiple" name="ids[]" size="10">'.$select_templates.'</select>';
submit_button('Export Table Builder Templates');
echo '</form>';
echo "<hr />";
$table_args = array(
'post_type' => 'tb_table',
'post_status' => 'any',
'numberposts' => '-1'
);
$table_posts = get_posts($table_args);
foreach ( $table_posts as $table_post ) {
$select_tables .= '<option value="'.$table_post->ID.'">'.$table_post->post_title.'</option>';
}
echo '<form method="post" action="" enctype="multipart/form-data">';
echo '<input type="hidden" name="post_type" value="tb_table" />';
echo '<select multiple="multiple" name="ids[]" size="10">'.$select_tables.'</select>';
submit_button('Export Table Builder Tables');
echo '</form>';
}
}
The problem was inside my form. Previously the name of the hidden input was post_type. I guess this messed with some stuff because after I got rid of the underscore, it worked.
echo '<input type="hidden" name="posttype" value="tb_template" />';
I currently work for a site where I need to create posts from Front End.
This is my code to create a custom post from frontend of wordpress site.
<?php
$postTitleError = '';
if (isset($_POST['submitted']))
{
if(trim($_POST['postTitle']) === '')
{
$postTitleError = 'Please enter a title.';
$hasError = true;
}
$post_information = array(
'post_title' => wp_strip_all_tags( $_POST['postTitle'] ),
'post_content' => $_POST['postContent'],
'post_type' => 'product',
'post_status' => 'publish'
);
wp_insert_post( $post_information );
}
?>
And this is my HTML Form:
<form action="" id="primaryPostForm" method="POST">
<!-- Title -->
<input class="addTitle" type="text" name="postTitle" id="postTitle" class="required" />
<!-- Description -->
<input class="addDescription required" name="postContent" id="postContent" />
<!-- Submit button -->
<button type="submit"><?php _e('Add Product', 'framework') ?></button>
</form>
I shown all my tags on the page but I don't know how to assign them into the post.
Currently i am able to create posts using my code but all i need is to add tags into my post.
Any idea?
Have you tried adding the following to your $post_information = array():
'tags_input' => array('tag,tag1,tag2');
So your code should look like:
$post_information = array(
'post_title' => wp_strip_all_tags( $_POST['postTitle'] ),
'post_content' => $_POST['postContent'],
'post_type' => 'product',
'post_status' => 'publish',
'tags_input' => array('tag,tag1,tag2')
);
This assumes you have enabled tags in your custom post type.
Reference:
http://www.templatemonster.com/help/wordpress-how-to-enable-and-output-post-tags-for-custom-post-types.html
http://stackoverflow.com/questions/10434686/wordpress-wp-insert-post-not-inserting-tags
http://stackoverflow.com/questions/12267422/update-and-add-tags-post-on-save-post-using-wp-update-post