wordpress plugin wp_editor doesn't post images - php

I'm trying to create a plugin with a visual editor and add media button that can POST and insert into the database all the HTML data. Here is my code:
<?php
if($_POST){
print_r($_POST);
global $wpdb;
$table_name = $wpdb->prefix . "eventi_ecm";
$name = $_POST['name'];
$text = $_POST['content'];
//$rows_affected = $wpdb->insert( $table_name, array( 'time' => current_time('mysql'), 'name' => $name, 'text' => $text ) );
}
$settings = array('textarea_name' => 'content','media_buttons' => true,'tinymce' => false);
?>
<div>
<h2>New Event</h2>
<form method="post" action="http://test.ble-group.com/wordpress/wp-admin/admin.php?page=eventi_new_page">
<div id="poststuff">
<input type="text" name="name"/>
<?php wp_editor( '', 'content', $settings ); ?>
</div>
</div>
<input type="hidden" name="action" value="update" />
<p><input type="submit"/></p>
</form>
</div>
But when I try to insert images, the HTML code about the image it's stripped. :(

I found this article which might help you.
In short, article suggests to use this code:
<?php wp_editor( stripslashes($content), $editor-id ); ?>
and this code to display the output:
<?php echo wpautop(stripslashes($editor-id)); ?>

thanks #user850010, but didn't worked, I solved this way:
echo '<pre>' . htmlspecialchars( stripslashes($_POST['content']) ) . '</pre>';

Related

Why updating meta from front-end needs i get old value?

The new value is sent to the db and the page refreshes on submit, but the field
becomes empty. If I then manually refresh the page again, then I see
the new value. Any idea why?
<form action="" method="POST" class="myForm" autocomplete="off">
<input id="dateChange" type="text" name="input-test" value="<?php echo str_replace('_', '', $jikuDate); ?>" autocomplete="off">
<input id="test-form" type="submit" name="updateDate" value="Update">
</form>
and then I do
<?php
if(isset($_POST['updateDate'])){
$post = array(
'ID' => $id
);
if ('Update' === ($_POST['updateDate'] ?? false)) {
update_post_meta( $post->ID, 'usp-custom-14', $_POST['input-test']);
}
}
?>
This is how I resolved it, not the most elegant probably:
First:
<?php
$jikuDate = get_post_meta($post->ID, 'usp-custom-14', true);
if (isset($_POST['updateDate'])) {
// Execute this code if the submit button is pressed.
$jikuDate = $_POST['input-test'];
}
?>
Then the html:
<form action="" method="POST" class="myForm" autocomplete="off">
<input id="dateChange" type="text" name="input-test" value="<?php echo str_replace('_', '', $jikuDate); ?>" autocomplete="off">
<input id="test-form" type="submit" name="updateDate" value="Update">
</form>
Then:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
if ('Update' === ($_POST['updateDate'] ?? false)) {
$post = array(
'ID' => $id
);
$jikuDate = $_POST['input-test'];
update_post_meta( $post['ID'], 'usp-custom-14', $_POST['input-test']);
}
}
?>

wp_redirect gives header already send error

I am trying to build a wordpress plugin that gets info from my form and puts it in muy database. This works perfectly fine but whenever i try to redirecty the page to the page where you can edit the items i get an error that the headers are already send. I tried everything from putting the get_header(); below the redirect to trying to work with hooks buth nothing works. There must be something that I am missing here.
<?php
global $wpdb;
$path='admin.php?page=my_pirazzo_locations';
$path2='admin.php?page=my_pirazzo_items';
$url=admin_url($path);
$url2=admin_url($path2);
//global $wpdb;
$userdb = $wpdb->prefix. 'users';
$getdata = $wpdb->get_results("SELECT * FROM $userdb");
//if (isset($_GET['id']))
//{
// $id= $_GET['id'];
// echo $id;
//}
//echo $userdb;
if (isset($_POST["submit"]) && $_POST["client"] != "" && $_POST["startdate"] != "" && $_POST["enddate"] != "") {
global $wpdb;
$userdb = $wpdb->prefix . 'users';
$table = $wpdb->prefix . "b2bdomain";
$user_id = strip_tags($_POST["client"]);
$startdate = strip_tags($_POST["startdate"]);
$enddate = strip_tags($_POST["enddate"]);
$isActive = 0;
if ($startdate < $enddate) {
$isActive = 1;
}
$query = $wpdb->get_results("SELECT user_login FROM $userdb WHERE ID = $user_id");
$name = $query[0]->user_login;
$wpdb->insert(
$table,
array(
'userid' => $user_id,
'isActivated' => $isActive,
'name' => $name,
'start_time' => $startdate,
'end_time' => $enddate,
)
);
$url = 'admin.php?page=my_pirazzo_edit';
ob_clean();
ob_start();
wp_redirect($url);
};
?>
<!-- This file should primarily consist of HTML with a little bit of PHP. -->
<div class="wrap">
<h1>beheer zone</h1>
<div class="postbox">
<div class="meta-th">
<h2>nieuwe zone toevoegen</h2>
</div>
<div class="meta-td">
<form method="post" name="cleanup_options" action="">
<fieldset>
<label for="client">Selecteer een Klant</label>
<select name="client" id="client">
<?php foreach($getdata as $data){ ?>
<option value="<?php echo $data->ID ?>"><?php echo $data->user_login ?></option>
<?php } ?>
</select>
</fieldset>
<fieldset>
<label for="startdate">Startdatum</label>
<input type="date" name="startdate" >
<label for="enddate">Einddatum</label>
<input type="date" name="enddate" >
</fieldset>
<?php submit_button('bewaar de zone', 'primary','submit', TRUE); ?>
</form>
</div>
</div>
<hr>
<div class="postbox">
<h2>voeg locatie's toe</h2>
<button class="button-primary">voeg een locatie toe</button>
</div>
<hr>
<div class="postbox">
<h2>voeg Producten toe</h2>
<button class="button-primary">voeg een locatie toe</button>
</div>
You can try sending your post data in wp_loaded hook. You can only use wp_redirect before header content is sent to the browser. So, instead of processing form in the template file. Moving them into wp_loaded hook might help you.
Please check below function for reference. Refer for https://cdn.tutsplus.com/wp/authors/legacy/tom/2012/09/25/wordpress-core-load-lifecycle.png
add_action( 'wp_loaded', 'pirazzo_edit_form' );
function pirazzo_edit_form(){
if( isset($_POST["submit"]) && $_POST["client"] != "" && $_POST["startdate"] != "" && $_POST["enddate"] != "") {
//YOUr additional code here
// process form, and then Redirect
$url = 'admin.php?page=my_pirazzo_edit';
wp_redirect($url);
exit();
}
}
Put the above code in your functions.php file to test it out.
Also, are you new to WordPress ? There are few things that hit me when i read your code properly. Now, there are many functions that comes built in with WordPress core for example querying the users. I see you have used wpdb object which you don't need to do.
This below is for your user selection field. Following is how we can query users directly using get_users function. Refer https://codex.wordpress.org/Function_Reference/get_users
<select name="client" id="client">
<?php $all_users = get_users(); ?>
<?php foreach($all_users as $data){ ?>
<option value="<?php echo $data->ID ?>"><?php echo $data->first_name .' ' .$data->last_name; ?></option>
<?php } ?>
</select>
Similarly, i do not see any nonce fields in your form submission. Please use nonce for security. Please check following on how we can implement this in WordPress.
<form method="post" name="cleanup_options" action="">
<?php
//Please check why this is needed https://codex.wordpress.org/Function_Reference/wp_nonce_field
wp_nonce_field( '_nonce_demo_action_field', '_demo_action_name' );
?>
Add the above code wp_nonce_field() below form or anywhere inside form. You are posting nonce secret data. So, we will be validating this when we are intercepting the post request sent like in the following:
//Functions.php
add_action( 'wp_loaded', 'pirazzo_edit_form' );
function pirazzo_edit_form(){
if( isset($_POST["submit"]) && wp_verify_nonce( $_POST['_demo_action_name'], '_nonce_demo_action_field' ) ) {
global $wpdb;
$userdb = $wpdb->prefix . 'users';
$table = $wpdb->prefix . "b2bdomain";
$user_id = strip_tags($_POST["client"]);
$startdate = strip_tags($_POST["startdate"]);
$enddate = strip_tags($_POST["enddate"]);
$isActive = 0;
if ($startdate < $enddate) {
$isActive = 1;
}
$query = $wpdb->get_results("SELECT user_login FROM $userdb WHERE ID = $user_id");
$name = $query[0]->user_login;
$wpdb->insert(
$table,
array(
'userid' => $user_id,
'isActivated' => $isActive,
'name' => $name,
'start_time' => $startdate,
'end_time' => $enddate,
)
);
$url = 'admin.php?page=my_pirazzo_edit';
wp_redirect( $url );
exit;
}
}
This above should be added in functions.php file. I have not touched anything inside the code. So, you will need to refactor it yourself.
Hope you understand the process i have written. Let me know on the comments if there are any confusions.

How to assign picture to every topic on a Q&A WordPress page?

I'm trying to assign a picture which users upload for every question and which should be displayed along with every question. I'm using the 'media_handle_upload' WordPress function to make the upload.
<div id="submit-question" class="dwqa-submit-question">
<?php
global $dwqa_options, $dwqa_current_error;
if( is_wp_error( $dwqa_current_error ) ) {
$error_messages = $dwqa_current_error->get_error_messages();
if( !empty($error_messages) ) {
echo '<div class="alert alert-error">';
foreach ($error_messages as $message) {
echo $message;
}
echo '</div>';
}
}
?>
<form action="" name="dwqa-submit-question-form" id="dwqa-submit-question-form" method="post">
<div class="question-advance">
<div class="question-meta">
<div class="select-category">
<label for="question-category"><?php _e('Question Category','dwqa') ?></label>
<?php
wp_dropdown_categories( array(
'name' => 'question-category',
'id' => 'question-category',
'taxonomy' => 'dwqa-question_category',
'show_option_none' => __('Select question category','dwqa'),
'hide_empty' => 0,
'quicktags' => array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,spell,close' ),
'selected' => (isset( $_POST['question-category'] ) ? stripslashes(htmlentities($_POST['question-category'])) : false)
) );
?>
</div>
<div class="input-tag">
<label for="question-tag"><?php _e('Question Tags','dwqa') ?></label>
<input type="text" name="question-tag" id="question-tag" placeholder="<?php _e('tag 1, tag 2,...','dwqa') ?>" value="<?php echo isset( $_POST['question-tag'] ) ? stripslashes(htmlentities($_POST['question-tag'])) : ''; ?>" />
</div>
</div>
</div>
<div class="input-title">
<label for="question-title"><?php _e('Your question','dwqa') ?> *</label>
<input type="text" name="question-title" id="question-title" placeholder="<?php _e('How to...','dwqa') ?>" autocomplete="off" data-nonce="<?php echo wp_create_nonce( '_dwqa_filter_nonce' ) ?>" value="<?php echo isset( $_POST['question-title'] ) ? stripslashes(htmlentities($_POST['question-title'])) : ''; ?>" />
<span class="dwqa-search-loading dwqa-hide"></span>
<span class="dwqa-search-clear fa fa-times dwqa-hide"></span>
</div>
<div class="question-advance">
<div class="input-content">
<label for="question-content"><?php _e('Question details','dwqa') ?></label>
<?php
dwqa_init_tinymce_editor( array(
'content' => ( isset( $_POST['question-content'] ) ? stripslashes(htmlentities($_POST['question-content'])) : '' ),
'id' => 'dwqa-question-content-editor',
'textarea_name' => 'question-content',
'media_buttons' => true
) );
?>
</div>
<?php if( isset($dwqa_options['enable-private-question']) && $dwqa_options['enable-private-question'] ) : ?>
<div class="checkbox-private">
<label for="private-message"><input type="checkbox" name="private-message" id="private-message" value="true"> <?php _e('Post this Question as Private.','dwqa') ?> <i class="fa fa-question-circle" title="<?php _e('Only you as Author and Admin can see the question', 'dwqa') ?>"></i></label>
</div>
<?php endif; ?>
<div class="question-signin">
<?php do_action( 'dwqa_submit_question_ui' ); ?>
</div>
<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
</script>
<?php
global $dwqa_general_settings;
if( dwqa_is_captcha_enable_in_submit_question() ) {
$public_key = isset($dwqa_general_settings['captcha-google-public-key']) ? $dwqa_general_settings['captcha-google-public-key'] : '';
echo '<div class="google-recaptcha">';
echo recaptcha_get_html($public_key);
echo '<br></div>';
}
?>
</div>
<div class="form-submit">
<input type="submit" value="<?php _e('Ask Question','dwqa','Upload') ?>" class="dwqa-btn dwqa-btn-success btn-submit-question" name="submit_my_image_upload"/>
</div>
</form>
My code starts below:
<form id="featured_upload" method="post" action="#" enctype="multipart/form-data">
<input type="file" name="my_image_upload" id="my_image_upload" multiple="false" />
<input type="hidden" name="post_id" id="post_id" value="55" />
<?php wp_nonce_field( 'my_image_upload', 'my_image_upload_nonce' ); ?>
<input id="submit_my_image_upload" name="submit_my_image_upload" type="submit" value="Upload" />
</form>
<?php
if (
isset( $_POST['my_image_upload_nonce'], $_POST['question-category'] )
&& wp_verify_nonce( $_POST['my_image_upload_nonce'], 'my_image_upload' )
) {
// The nonce was valid and the user has the capabilities, it is safe to continue.
// These files need to be included as dependencies when on the front end.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
// Let WordPress handle the upload.
// Remember, 'my_image_upload' is the name of our file input in our form above.
$attachment_id = media_handle_upload( 'my_image_upload', $_POST['question-category'] );
if ( is_wp_error( $attachment_id ) ) {
// There was an error uploading the image.
echo 'Error uploading';
} else {
// The image was uploaded successfully!
}
} else {
// The security check failed, maybe show the user an error.
}?>
</div>
This is the question-submitt-form.php of the plugin and I'm pretty sure I should implement the 'media_handle_upload' function inside the form so every uploaded picture will get the id of the question and with the press of submit the picture will be related with the question, but can't make it work. When it's out of the first "form" it's uploading pictures but they are not related with the questions.
PS: If there is another solution to accomplish this (Q&A Reddit, Stack Overflow style and image assign to every question I'm open for suggestions).
I have some advancement in the task: Adding:
add_post_type_support('dwqa-question', array('thumbnail'));
add_theme_support('post-thumbnails');
in the functions.php alows me to asign featured image from the back end wich i show in front end with:
<div class="topic_image"><?php the_post_thumbnail('thumbnail');?></div>
Now the problem is how to assign featured image from the front end. I came up with the folowing code wich looks logical but doesn't work
<input type="file" name="imageFeatured" id="imageFeeatured"/>
<?php
if ( ! empty( $_POST[ 'post-thumbnails' ] ) )
$thumbnail_field = esc_html( $_POST[ 'post-thumbnails' ] );
else
$thumbnail_field = 'imageFeatured';
if ( ! empty( $_FILES ) ) {
foreach ( $_FILES as $file => $array )
$newupload = insert_attachment( $file, $pid, $thumbnail_field );
}
//attachment helper function
function insert_attachment( $file_handler, $post_id, $set_thumb = false ) {
if ( UPLOAD_ERR_OK !== $_FILES[ $file_handler ]['error'] )
return false;
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
$attach_id = media_handle_upload( $file_handler, $post_id );
//set post thumbnail (featured)
if ( $attach_id && $set_thumb )
update_post_meta( $post_id, 'thumbnail', $attach_id );
return $attach_id;
}
?>

Clear form after submit and page refresh - Wordpress

I know that the correct way to insert the data is using AJAX, but I don't mind if the page refreshes. Can anybody help me clear the form data after the page refreshes? Everything works fine, the data is being submitted to the table, and the page refreshes. But if I hit the refresh button again, it tells me that the data will be submitted ... and I don't know what to do.
<?php
$current_user = wp_get_current_user();
if ( $current_user->ID == 0 ) {
} else {
if( isset( $_POST['drop_artists'] ) ) {
$answer = $_POST['drop_artists'];
}else{
$answer = $_POST['artist_name'];
}
$date = current_time( 'mysql' );
$table = "t4t5_answers";
$sql = $wpdb->prepare( "INSERT INTO $table (user_id, post_id, info, answer, submission_date ) VALUES ( %d, %d, %s, %s, %d )", $current_user->ID, $post->ID, 'artist', $answer, $date );
$wpdb->query($sql);
header('Location: ' . get_bloginfo('url'));
}//if(isset($_POST['form_sub']))
?>
<form method="post" action="" id="artists-form">
<ul>
<li id="categories">
<?php
$args = array(
'show_option_all' => 'Artists',
'hierarchical' => 1,
'child_of' => 406,
'order_by' => 'name',
'name' => 'answer',
'hide_empty' => 0
);
wp_dropdown_categories($args); ?>
</li>
</ul>
<input type="text" name="artist_name" value="" size="45" id="input-title"/>
<input id="submitButton" class="subput" type="submit" name="submit" value="Add"/>
</form>
After the page is posted, use a redirect to send te user to a success page. This will make the page that was actually posted not appear in their history.
if (!empty($_POST)) {
// do stuff
header("Location: $_SERVER[PHP_SELF]");
}
Note the URL for the redirect should be a full URL, not a relative one. In practice though, I haven't seen any browsers have a problem with the relative URL.
To redirect to your current url immediately, try this one
echo '<META HTTP-EQUIV=Refresh CONTENT="0; URL='.$current_URL.'">'
for more details see http://en.wikipedia.org/wiki/Meta_refresh
Write your php code inside if(isset($_POST['submit']) and add following script below insert statement.
echo " <script type='text/javascript'>
window.location=document.location.href;
</script>";
Your code will look like the following:
global $wpdb,$post;
if(isset($_POST['submit']))
{
$current_user = wp_get_current_user();
if ( $current_user->ID == 0 )
{
}
else
{
if( isset( $_POST['drop_artists'] ) )
{
$answer = $_POST['drop_artists'];
}
else
{
$answer = $_POST['artist_name'];
}
$date = current_time( 'mysql' );
$table = "t4t5_answers";
$sql = $wpdb->prepare( "INSERT INTO $table (user_id, post_id, info, answer, submission_date ) VALUES ( %d, %d, %s, %s, %d )", $current_user->ID, $post->ID, 'artist', $answer, $date );
$wpdb->query($sql);
}
echo "<script type='text/javascript'>
window.location=document.location.href;
</script>";
}
?>
<form method="post" action="" id="artists-form">
<ul>
<li id="categories">
<?php
$args = array(
'show_option_all' => 'Artists',
'hierarchical' => 1,
'child_of' => 406,
'order_by' => 'name',
'name' => 'answer',
'hide_empty' => 0
);
wp_dropdown_categories($args); ?>
</li>
</ul>
<input type="text" name="artist_name" value="" size="45" id="input-title"/>
<input id="submitButton" class="subput" type="submit" name="submit" value="Add"/>
</form>
This will refresh your page after form submit and form values will not be resubmitted.

Publish a custom post type from front

I want to publish a custom post type 'question' from the front-end, but when I submit the form I keep getting 404 error. Bellow is the form and form processing. What am I doing wrong?
<?
/**
* Questions processing
*/
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please add a question';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please add a description';
}
// Add the content of the form to $post as an array
$post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => 'question'
);
wp_insert_post($post); // Pass the value of $post to WordPress the insert function
} // end IF
// Do the wp_insert_post action to insert it
do_action('wp_insert_post', 'wp_insert_post');
?>
<h1>Add a question:</h1>
<!-- New Question Form -->
<div>
<form name="new_post" method="post" action="">
<p><label for="title">Question:</label><br />
<input type="text" value="" name="title" />
</p>
<p><label for="description">Details</label><br />
<textarea name="description" cols="50" rows="6"></textarea>
</p>
<p><input type="submit" value="Ask!" name="submit" /></p>
<input type="hidden" name="post_type" value="question" />
<input type="hidden" name="action" value="new_post" />
<?php wp_nonce_field( 'new-post' ); ?>
</form>
</div>
<!--// New Question Form -->
You don't actually need the add_action bit and I have a feeling is the $post variable itself that's causing issues.
/**
* Questions processing
*/
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
// Do some minor form validation to make sure there is content
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please add a question';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please add a description';
}
// Add the content of the form to $post as an array
$new_post = array(
'post_title' => $title,
'post_content' => $description,
'post_status' => 'publish',
'post_type' => 'question'
);
$id = wp_insert_post($new_post); // Pass the value of $post to WordPress the insert function
//Returns ID of the new post you just created
And just in case, also add a URL to your form tag:
<form name="new_post" method="post" action="<?php the_permalink(); ?>">
I figured out:
I've deleted the line:
<input type="hidden" name="post_type" value="question" />
I think Wordpress is using somehow a post variable with this name and it get's an error if I use it on my own.

Categories