Add html/PHP pages on plugin activation (Wordpress) - php

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

Related

Wordpress wp_insert_post is creating new Taxonomy term when creating new custom post

In my WordPress v5.5.1, I am using public front-end form to create custom post type. I am saving the form data as custom post with below code:
function save_function() {
// MESSAGE FIELDS
$public_post = array(
'post_title' => filter_input(INPUT_POST, 'title'),
'post_author' => 1,
'post_type' => 'message',
'post_status' => 'pending',
'tax_input' => array(
'my_custom_taxonomy' => array(filter_input(INPUT_POST, 'subject')) // subject is a HTML select which captures option value contains term_id which is generated using get_terms.
)
);
wp_insert_post($public_post);
}
Instead of 'tax_input' tag this post to the existing custom_taxonomy term, it is creating a duplicate term with term_id as term name.
Hello Plese Try This Func
function save_function()
{
$subject_term = 'subject';
$my_subject_term = term_exists($subject_term, 'my_custom_taxonomy'); // check if term in website or no
// Create Term if it doesn't exist
if (!$my_subject_term) {
$my_subject_term = wp_insert_term($subject_term, 'my_custom_taxonomy');
}
$custom_tax = array(
'my_custom_taxonomy' => array(
$my_subject_term['term_taxonomy_id'],
)
);
// MESSAGE FIELDS
$public_post = array(
'post_title' => filter_input(INPUT_POST, 'title'),
'post_author' => 1,
'post_type' => 'message',
'post_status' => 'pending',
'tax_input' => $custom_tax
);
$post_id = wp_insert_post($public_post);
}

Duplication of message when adding to DB in wordpress

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.

Add page template to a custom page using custom plugin wordpress

I am new to developing the wordpress plugin. I am developing a plugin and I have succeeded in creating a new page whenever the plugin is activated but I want to add a custom php template file to that page. Thats means on activation I want to create a custom page with a custom template. Is it possible to do?
To create a new page I have used this code but could not find anything on adding the template thing:
register_activation_hook(__FILE__,'my_plugin_install');
function my_plugin_install() {
global $wpdb;
$the_page_title = 'Custom Cart';
$the_page_name = 'cart';
delete_option("Custom Cart");
add_option("Custom Cart", $the_page_title, '', 'yes');
delete_option("cart");
add_option("cart", $the_page_name, '', 'yes');
delete_option("my_plugin_page_id");
add_option("my_plugin_page_id", '0', '', 'yes');
$the_page = get_page_by_title( $the_page_title );
if ( ! $the_page ) {
$_p = array();
$_p['post_title'] = $the_page_title;
$_p['post_content'] = "This text may be overridden by the plugin. You shouldn't edit it.";
$_p['post_status'] = 'publish';
$_p['post_type'] = 'page';
$_p['comment_status'] = 'closed';
$_p['ping_status'] = 'closed';
$_p['post_category'] = array(1);
$the_page_id = wp_insert_post( $_p );
}
else {
$the_page_id = $the_page->ID;
$the_page->post_status = 'publish';
$the_page_id = wp_update_post( $the_page );
}
delete_option( 'my_plugin_page_id' );
add_option( 'my_plugin_page_id', $the_page_id );
}
This is a simple way to create a page with attach template in WordPress. To create a new page I have used this code:
register_activation_hook(__FILE__,'my_plugin_install');
function my_plugin_install() {
$the_slug = 'cart';
$args = array(
'name' => $the_slug,
'post_type' => 'page',
'post_status' => 'publish',
'numberposts' => 1
);
$my_posts = get_posts($args);
if(empty($my_posts)){
$my_post = array(
'post_title' => 'Custom Cart',
'post_content' => '',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page',
'post_name' => 'cart'
);
// Insert the post into the database
$post_id=wp_insert_post( $my_post );
update_post_meta( $post_id, '_wp_page_template', 'page-templates/cart.php' ); // optional to add page template
}
}
Add custom page template: /theme/your-theme-name/page-templates/cart.php:
<?php
/*
* Template Name: Custom Cart Page
*/
get_header(); ?>
HTML code here ..
<?php get_footer();?>

Wordpress Plugin - Delete a Page Created when deactivating

I tried to make a custom post type plugin for my own use, and managed to make a function that creates the page for it so far. What I want to do is to delete the said page when the plugin is activated. How should the code be?
This is my code for creating the said page upon plugin activation:
function create_video_pages() {
$post = array(
'comment_status' => 'open',
'ping_status' => 'closed' ,
'post_date' => date('Y-m-d H:i:s'),
'post_name' => 'videos',
'post_status' => 'publish' ,
'post_title' => 'Videos',
'post_type' => 'page',
);
$newvalue = wp_insert_post( $post, false );
update_option( 'vidpage', $newvalue );
}
Get the post_id from your vidpage option.
Then use it to delete that post.
function deactivate_plugin() {
$page_id = get_option('vidpage');
wp_delete_post($page_id);
}
register_deactivation_hook( __FILE__, 'deactivate_plugin' );
You can do this using register_deactivation_hook and function wp_delete_post which deletes post with everything that is tied to it.
What about this?
function on_deactivating_your_plugin() {
$page = get_page_by_path( 'about' );
wp_delete_post($page->ID);
}
register_deactivation_hook( __FILE__, 'on_deactivating_your_plugin' );

wordpress create duplicate post on save / update

I know this might seem strange to some, but i would like to duplicate a post on creation.
When a post is created, i would like to duplicate it appending new data to the title, as well as updating meta fields and changing the taxonomy it is in.
Here is what i have done so far:
add_action('wp_insert_post', 'my_add_custom_fields');
function my_add_custom_fields($post_id)
{
if ( $_POST['post_type'] == 'products' ) {
$my_post = array(
'post_title' => get_the_title(),
'post_content' => '',
'post_status' => 'publish',
'post_type' => 'products',
);
$id = wp_insert_post($my_post);
update_post_meta($id,'keywords', get_the_title());
wp_set_object_terms($id, 'New Term Here', 'platform');
}
return true;
}
The issue i have is this creates an endless loop, creating the new post thousands of times and wont stop until i restart apache.
Is there away around this?
You need some sort of control for this to stop it looping. e.g. set a global value to count
$GLOBALS['control']=0;
add_action('wp_insert_post', 'my_add_custom_fields');
function my_add_custom_fields($post_id)
{
if ( $_POST['post_type'] == 'products' ) {
//if control is on third iteration dont proceed
if($GLOBALS['control']===2)
return;
//add control here!
$GLOBALS['control']++;
$my_post = array(
'post_title' => get_the_title(),
'post_content' => '',
'post_status' => 'publish',
'post_type' => 'products',
);
$id = wp_insert_post($my_post);
update_post_meta($id,'keywords', get_the_title());
wp_set_object_terms($id, 'New Term Here', 'platform');
}
return true;
}

Categories