Calling PHP function from HTML form on same page - php

So I have looked around online and found some questions on here about it, but nothing seemed to work for my situation.
I have a form which should call a function that is set on the page.
The form's html is as follows:
<form method="post" action="">
<textarea id="input-box" placeholder="What's on your mind?" maxlength="10000" name="quick-post-area" class="col-md-offset-2 col-md-6"></textarea>
<input type="submit" value="Post" class="col-md-2" id="quick-post-submit">
</form>
and the function:
// Initialize the page ID to -1. This indicates no action has been taken.
$post_id = -1;
$author_id = 1;
$slug = 'post';
global $current_user;
// If the page doesn't already exist, then create it
if( null == get_page_by_title( $title ) ) {
// Set the post ID so that we know the post was created successfully
$pollq_question = wp_kses_post( trim( $_POST['pollq_question'] ) );
$post_id = wp_insert_post(
array(
'comment_status' => 'open',
'ping_status' => 'closed',
'post_author' => $current_user->ID,
'post_name' => $slug,
'post_title' => 'Posted By:' . $current_user->ID,
'post_status' => 'publish',
'post_type' => 'post',
'post_content' => $_POST['quick-post-area']
)
);
// Otherwise, we'll stop
} else {
// Arbitrarily use -2 to indicate that the page with the title already exists
$post_id = -2;
} // end if
} // end programmatically_create_post
and finally the isset that I am trying to use to call the function:
if(isset($_POST['submit']))
{
quick_post();
}
Anyone got any ideas about what I need to change for it to fire?

This line is searching for an object with the name submit on it
if(isset($_POST['submit']))
{
But your form doesn't have such object, so add a name to your input and the function shall work:
<input type="submit" name="submit" value="Post" class="col-md-2" id="quick-post-submit">

<input type="submit" value="Post" class="col-md-2" id="quick-post-submit">
vs
if(isset($_POST['submit']))
{
quick_post();
}
you didn't give the submit button a name="submit" attribute

Related

Adding my custom post type from plugin to my search results

I am not able to get search results for my custom post type, generated by a plugin I'm using in wordpress.
If I change the URL after searching from domain.com/?s=searchterm
to domain.com/?s=searchterm&post_type=customposttype, it displays only the search results for this custom post type.
My custom post type is searchable and visible.
I used also these settings in my custom post type.
'query_var' => true,
'exclude_from_search' => false,
I used also these settings in my custom post type:
'query_var' => true,
'exclude_from_search' => false,
I have this line in my searchform.php file:
if ( 'any' != $post_type ) {<input type="hidden" name="post_type" value="post, customposttype" />}
How can I make the search results return results of both post and the customposttype?
in searchform.php
<form method="get" class="searchform" id="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="text" class="field" name="s" id="s" placeholder="<?php esc_html_e( 'Search', 'oceanwp' ); ?>">
<input type="hidden" name="post_type[]" value="post" />
<input type="hidden" name="post_type[]" value="customposttype" />
</form>
in functions.php
function mySearchFilter($query) {
$post_type = $_GET['post_type'];
if (!$post_type) {
$post_type = 'any';
}
if ($query->is_search) {
$query->set('post_type', $post_type);
};
return $query;
};
add_filter('pre_get_posts','mySearchFilter');
You need to find the actual query and set the post_type to 'any'.
$query = new WP_Query( array( 'post_type' => 'any', 's' => $search_term ) );
An alternative is to create a filter for search queries, which may be easier (and probably better practice) than adjusting theme code.
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', 'any');
}
}
}
add_action('pre_get_posts','search_filter');

WordPress custom shortcode breaks saving process (post.php)

I'm experiencing a strange issue with shortcodes in WordPress. When I save the page while the shortcode is added, it redirects me to wp-admin/post.php and shows me a white page with the results of the shortcode in html format (see screenshot 1). Luckily, all the editing is saved.
The funny thing is that I've done this a dozen times with the exact same method. But for a short while now it doesn't work anymore.
I do hope you see the issue and know what we can do to fix it.
Screenshot 1
The PHP code that I'm using is added to the functions.php
The shortcode that I'm using is [showblog cat="planning" number=4]
function showblog_func( $atts ) {
$atts = shortcode_atts([
'number' => '-1',
'cat' => '',
], $atts, 'showblog' );
$numberposts = $atts['number'];
$categorie = $atts['cat'];
//args
$args = array(
'post_type' => 'post',
'posts_per_page' => $numberposts,
'order' => 'ASC',
);
if($categorie != ""){
$args = array(
'post_type' => 'post',
'posts_per_page' => $numberposts,
'category_name' => $categorie,
'order' => 'ASC',
);
}
// The Query
$the_query2 = new WP_Query( $args );
// The Loop
if ( $the_query2->have_posts() ) {
echo '<ul class="blog-list clearfix">';
while ( $the_query2->have_posts() ) {
$the_query2->the_post();
echo '<li class="blog-block">';
echo ' <div class="blog-info">';
echo ' <h4>'.get_the_title().'</h4>';
echo ' <p>'.get_the_excerpt().'</p>';
echo ' Read full post';
echo ' </div>';
echo '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
}
add_shortcode( 'showblog', 'showblog_func' );
It's solved by adding ob_start(); right after the first <?php tag.
I had the same and found the way to fix
just add ob_start(); before html start and ob_get_clean(); to end like this
function form_creation(){
ob_start();
?>
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br>
Message: <textarea name="message"> Enter text here...</textarea>
</form>
<?php
return ob_get_clean();
}
add_shortcode('test', 'form_creation');
You can't echo the shortcode HTML.
You need to bind HTML in variable and then return this HTML from shortcode..
Please check the code below
function _login_popup() {
$html = '<form id="user-login-form" method="post" action="#" class="js-form-redirect js-form-action" novalidate="">
<div class="floating-label form-group">
<input id="useremail" name="user_name" required="" value="" type="email">
<label for="useremail">Email</label>
</div>
<div class="floating-label form-group">
<input id="userpassword" name="password" required="" value="" type="password">
<label for="userpassword">Password</label>
</div>
<div class="o-form__buttons text-right --small-center">
<button type="submit" id="submit_login" class="a-button-form --save a-no-before" value="edit">Sign in</button>
</div>
</form>';
return $html;
}
add_shortcode('yg-login-popup', '_login_popup');

function wp_insert_post() inside single-{customposttype}.php clearing custom fields

i have single-mypost.php to display mypost single post, in which user can submit a form for msgs (msgs is another custom post type for private messages). when user submits form new post is perfectly added to msgs but single mypost customfields are changing to empty. i have added code am using
<form method="post" action="" class="gform" onSubmit="return validatebid()">
<h2>Message</h2>
<input type="hidden" name="msgfor" value="<?php echo $post->ID; ?>"/>
<input type="hidden" name="msgby" value="<?php echo get_current_user_id(); ?>"/>
<input type="hidden" name="msgdate" value="<?php echo date('Y-m-d H:i:s'); ?>"/>
<div class="row">
<label>Message</label>
<div class="field">
<textarea name="textareafield"></textarea>
</div>
</div>
<div class="row">
<input type="hidden" name="task" value="msg" />
<input type="submit" name="submit" class="red-btn" value="Message Now"/>
</div>
</form>
once user submits form am using wp_insert_post to insert post. code i have added before get_header.
if ( isset( $_POST[ 'task' ] ) && $_POST[ 'task' ] == 'msg' ) {
$post_info = array(
'post_title' => wp_strip_all_tags( $_POST[ "msgfor" ] . '-' .
$_POST[ "msgby" ] . '-' . $_POST[ "msgdate" ] ),
'post_content' => $_POST[ 'textareafield' ],
'post_type' => 'msgs',
'post_status' => 'publish'
);
$pid = wp_insert_post( $post_info );
echo $pid;
update_post_meta( $pid, "msgfor", $_POST[ "msgfor" ] );
update_post_meta( $pid, "msgby", $_POST[ "msgby" ] );
update_post_meta( $pid, "msgdate", $_POST[ "msgdate" ] );
}
Please add
<?php if ( isset( $_POST[ 'textareafield' ] ) ) {
echo $_POST[ 'textareafield' ];
}?>
between <textarea name="textareafield"></textarea>
I think the second part of the code should be in a separate file, it will look something like this:
require('wp-load.php'); // make sure that it is the correct path to this file
... your code here ...
As an option, make the form submission via AJAX, with wp_ajax_ action hook.
The key idea is not using wp_insert_post() inside your single-mypost.php template.

update mysql datatable using checkbox in loop form

i'm trying to update a custom table for my wordpress plugin, first im getting the roles from my table then display it using a form and this works fine, now the problem is that when i check the boxs it update in database, but when i uncheck it, it dont update at all and if i uncheck it all i get this error message
Warning: Invalid argument supplied for foreach() in C:\wamp\www\wp_test\wp-content\plugins\Data\settings.php on line 52
<?php
$roles=get_editable_roles();
global $wpdb;
$table_name = $wpdb->prefix. "Author_detailed_repport";
?>
<h3>Settings Page</h3>
<h4>Add/Remove a role from filter list</h4>
<p>This setting allow you to add/remove roles from the filter<br />
list, here down a list of all the roles existing in your website, all<br />
you have to do is to check/uncheck wich you wanna add/rmove from filter list</p>
<form action="<?php $_REQUEST['PHP_SELF'] ?>" method="post">
<?php
require_once('../wp-config.php');
$i=0;
foreach($roles as $role)
{
$rom=$role['name'];
$results = $wpdb->get_results( "SELECT * FROM ".$table_name." WHERE role= '".$rom."'" );
if ($results==NULL)
{$wpdb->insert( $table_name, array(
'role' => $role['name'],
'statut' => '',
'post_number' => '',
'activate' => ''
));
}?>
<input type="checkbox" name="cat[]" value="<?php echo $i+1 ;?>" <?php checked($results[0]->statut, $i+1); ?> />
<input type="hidden" name="ww" value="0">
<?php
?>
<label>
<?php echo $results[0]->role;?></label><br />
<?php $i++; } ?>
<input type="submit" value="save" name="saveme" />
</form>
<?php
if(isset($_POST['saveme']))
{
$cats=$_POST['cat'];
foreach($cats as $cam)
{
if(isset($cam))
{
$wpdb->update( $table_name, array(
'statut' => $cam
),array('ADR_id' => $cam),array('%d'));}
else
{
$wpdb->update( $table_name, array(
'statut' => '0'
),array('ADR_id' => $cam),array('%d'));
}
}
}
?>
Because $roles is not set yet and there you need to do a another check
If(isset($roles)) {
//foreach loop goes in here
}

Setting featured image from front end form

So I have been trawling the internet for a few days looking for a solution to this problem. I am trying to set the featured image of a post from the upload input of this form:
<form method="post" action="" id="quick-post-form" enctype="multipart/form-data">
<textarea id="input-box" placeholder="What's on your mind?" maxlength="10000" name="quick-post-area" class="col-xs-12"></textarea>
<!-- images -->
<fieldset class="images">
<label for="images">Upload an image</label>
<input type="file" name="image-uploader" id="img-upload" size="50">
</fieldset>
<!-- images end -->
<input type="submit" value="Post" name="submit" class="col-md-4 col-xs-12" id="quick-post-submit">
</form>
I am using wp insert post to create a post from this form but the image is not uploaded as it should be. This is the PHP I'm using:
<?php
function quick_post() {
// Initialize the page ID to -1. This indicates no action has been taken.
$post_id = -1;
$author_id = 1;
$slug = 'post';
global $current_user;
$user_id = get_current_user_id();
// If the page doesn't already exist, then create it
if( null == get_page_by_title( $title ) ) {
$post_id = wp_insert_post(
array(
'comment_status' => 'open',
'ping_status' => 'closed',
'post_author' => $user_id,
'post_name' => $slug,
'post_title' => 'Post By: ' . $current_user->user_login,
'post_status' => 'publish',
'post_type' => 'post',
'post_content' => $_POST['quick-post-area'],
'post_category' => array( 3 ),
)
);
require_once (ABSPATH.'/wp-admin/includes/media.php');
require_once (ABSPATH.'/wp-admin/includes/file.php');
require_once (ABSPATH.'/wp-admin/includes/image.php');
$attachmentId = media_handle_upload('image-uploader', $post_ID);
set_post_thumbnail($post_ID, $attachmentId);
// Otherwise, we'll stop
} else {
// Arbitrarily use -2 to indicate that the page with the title already exists
$post_id = -2;
} // end if
} // end programmatically_create_post
if(isset($_POST['submit']))
{
quick_post();
header('Location: https://outrankd.com');
}
?>
I should also mention that once this is working, I plan to use the Wordpress check filetype function to validate the upload but think that this should work with something like this:
if ($attachmentId = wp_check_filetype('image')) {
set_post_thumbnail($post_ID, $attachmentId);
}
If anyone could shed some light on where I'm going wrong, it would be much appreciated.
Thanks

Categories