I am trying to insert a post/page and then save the post id as an option, but the option is not saving to the database.
I am able to create the page and get the ID of it, but I am unable to save that ID to the options. The class is called at "init" and the constructor is as follows:
class Recipe{
public function __construct(){
$favorites_id = get_option("favoritesid");
if($favorites_id <= 0){
$my_post = array(
'post_title' => 'Favorites',
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page'
);
$result_id = wp_insert_post( $my_post );
if($result_id > 0){
add_option("favoritesid", $result_id);
}
}
}
Test the code in the main plugin file: (//use array_push for option)
class Recipe{
public function __construct(){
add_action('init',[$this,'test']);
}
public function test(){
$favorites_id = get_option("favoritesid",[]);
if($favorites_id >= 0){
$my_post = array(
'post_title' => 'this is test',
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page'
);
$result= get_page_by_title($my_post['post_title'],ARRAY_A, 'page');
if(is_null($result)) {
$result_id = wp_insert_post( $my_post );
if ( $result_id >= 0 ) {
update_option( "favoritesid", $result_id );
}
}
else return false;
}
}
}
new Recipe;
Related
there are meet the team pages on that page there are jobs in all pages and I want to show the job matching with owner name and in my jobs there are custom field name Owner I want to show the related jobs are per the owner name
function fl_builder_loop_query_args_filter_similar_author ( $args ) {
$mymoduleids = $args['settings']->id;
if($mymoduleids=="similar_author_module")
{
global $post;
$args = array(
'posts_per_page' => 6,
'post_type' => 'job_listing',
'post_status' => 'publish',
'author__in'=> array(get_user_id_by_display_name($post->post_title))
);
$jobs = new WP_Query( $args );
if(count($jobs->posts)==0){
$args = array(
'posts_per_page' => 6,
'post_type' => 'job_listing',
'post_status' => 'publish',
'order' => 'DESC',
);
}
return $args;
}
else{
return $args;
}
}
add_filter( 'fl_builder_loop_query_args', 'fl_builder_loop_query_args_filter_similar_author' );
function get_user_id_by_display_name( $display_name ) {
global $wpdb;
if (!$user = $wpdb->get_row($wpdb->prepare(
"SELECT `ID`
FROM $wpdb->users
WHERE `owner` = %s", $display_name
)))
return false;
return $user->ID;
}
there are meet the team pages on that page there are jobs in all pages and i want to show the job matching with owner name and in my jobs there are custom field name "Owner" i want to show the related jobs are per the owner name
function fl_builder_loop_query_args_filter_similar_author ( $args ) {
$mymoduleids = $args['settings']->id;
if($mymoduleids=="similar_author_module")
{
global $post;
$args = array(
'posts_per_page' => 6,
'post_type' => 'job_listing',
'post_status' => 'publish',
'author__in'=> array(get_user_id_by_display_name($post->post_title))
);
$jobs = new WP_Query( $args );
if(count($jobs->posts)==0){
$args = array(
'posts_per_page' => 6,
'post_type' => 'job_listing',
'post_status' => 'publish',
'order' => 'DESC',
);
}
return $args;
}
else{
return $args;
}
}
add_filter( 'fl_builder_loop_query_args', 'fl_builder_loop_query_args_filter_similar_author' );
function get_user_id_by_display_name( $display_name ) {
global $wpdb;
if (!$user = $wpdb->get_row($wpdb->prepare(
"SELECT `ID`
FROM $wpdb->users
WHERE `owner` = %s", $display_name
)))
return false;
return $user->ID;
}
I am trying to do a conditional check (checking if post with same post title exists) before running wp_insert_post() but it still accepts the insertion even if existing posts are found. I tried using post_exists(), but this function breaks the entire page for some reason. What am I doing wrong?
footer.php:
<?php
$statusmessage = '';
if (isset($_POST['footer-email'])){
$footer_email = $_POST['footer-email'];
$args = array(
"post_title" => $footer_email,
"post_type" => 'subscriptions',
"post_status" => 'publish',
);
$query = new WP_Query( $args );
if($query->have_posts()) {
$statusmessage = '<p class="subscription-confirmation">You have already signed up.</p>';
}
else {
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
} // end else
wp_reset_postdata();
} // end if isset footer email
?>
You can use post_exists(). check the below cood.
<?php
$statusmessage = '';
if (isset($_POST['footer-email'])){
$footer_email = $_POST['footer-email'];
if( ! post_exists( $footer_email ) ){
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
}
} // end if isset footer email
You can use get_page_by_title() to fetch subscribers by title.
$statusmessage = '';
if ( isset( $_POST['footer-email'] ) ){
$footer_email = $_POST['footer-email'];
$subscribers = get_page_by_title( $footer_email , OBJECT, 'subscribers' );
if( !$subscribers->ID ){
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
}
}
OR custom wpdb query.
global $wpdb;
$postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $footer_email . "'" );
if( !$postid ){
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
}
When i try to add one post to db using wp_insert_post() in db added two posts:
Ajax request:
/wp-admin/admin-ajax.php?action=getchats&chat_type=all-chat&last_msg=110&add_msg=true&chat_message=helloworlds
action for this:
add_action( 'wp_ajax_getchats', 'getchats');
function getchats(){
if (!isset($_GET['last_msg'])||(!is_numeric($_GET['last_msg'])||(!isset($_GET['chat_type'])))){
die(json_encode(array('error' => 'no_latest')));
}
$cat_id = get_cat_ID($_GET['chat_type']); //the categories name
if ((isset($_GET['add_msg']))&&(isset($_GET['chat_message']))){
$user_id = get_current_user_id();
$description = $_GET['chat_message'];
$title = $description;
if (strlen($title)>20){
$title = mb_substr($title, 0, 20, 'UTF-8');
}
$my_post = array(
'post_content' => $description,
'post_title' => $title,
'post_status' => 'publish',
'post_type' => 'chatmsg',
'post_author' => $user_id,
'post_category' => array($cat_id)
);
wp_insert_post($my_post);
}
$args=array(
'numberposts' => 3,
'orderby' => 'ID',
'category' => $cat_id,
'post_type' => 'chatmsg',
'post_status' => 'publish',
);
$messages = [];
$posts = get_posts($args);
die(json_encode($posts));
foreach( $posts as $post ){
if ($post->ID > $_GET['last_msg']){
$row = array(
'id' => $post->ID,
'message'=>$post->post_content,
'author'=>$post->post_author,
'date'=>$post->post_date,
);
$message[] = $row;
}
}
die(json_encode(array('error' => 'ok', 'messages'=> $messages)));
}
Why am i using only one wp_insert_post but receive two post?
UPD: Need use wp_doing_ajax for it. Thanks for answer Maxim Sarandi.
if( wp_doing_ajax() ) {
add_action('wp_ajax_getchats', 'getchats');
function getchats()
{
//some code
}
}
Maybe this or this might help you.
And can i give you a few recommendation to your code style?
First - use $_POST for similar queries.
Second - stop use die(wp_send_json()). Inside wp_send_json already present die(); Just use wp_send_json_error() for error response or wp_send_json_success(); or wp_send_json()
Third - use nonces and check_ajax_referer();
Fourth - stop cloning not needed brackets.
i am using this code to create a post in DWQA plugin? but, my theme editer is going to die. what's the problem i am facing?
function my_pre_save_post( $post_id ) {
// check if this is to be a new post
if( $post_id != 'new' )
{
return $post_id;
}
// Create a new post
$post = array(
'post_content'=> $post_content,
'post_title' => $post_title,
'post_author' => $post_author,
'post_category' => $post_category,
'post_type' => 'dwqa-question',
'post_status' => 'draft',
'post_date' => 'date_created',
'show_in_menu' => 'post-new.php?post_type=dwqa-question',
);
// insert the post
$post_id = wp_insert_post( $post );
// update $_POST['return']
$_POST['return'] = add_query_arg( array('post_id' => $post_id), $_POST['return'] );
// return the new ID
return $post_id;
}
add_filter('acf/pre_save_post' , 'my_pre_save_post' );
I was just a thought, but I have not tried.
you need / add functions in wp-includes / query.php
Such code:
function query_post($post_id) {
$GLOBALS['wp_query'] = new WP_Query();
return $GLOBALS['wp_query']->query($post_id);
}
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