Hi I am developing a word press website. I created a custom template, where in I have a form and fields are inserted into the database(mySql). The Codes are shown below.Insert into database
Now I require to display the data which are already inserted into the database in front end in form of a table or grid. How I am able to do that.
I need the output something like this.
Ritual Name Ritual Active
---------------------------
Test1 | Y
Test2 | Y
Any help appreciated.
function.php
function childtheme_style_andscripts(){
//wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css' );
wp_enqueue_script('ajax-function', get_stylesheet_directory_uri() . '/js/ajaxfunction.js', array('jquery'), '1.0', true );
wp_localize_script( 'ajax-function', 'usersubmitform', array(
'url'=> admin_url('admin-ajax.php'),
'security'=> wp_create_nonce('our-nonce')
) );
}
add_action('wp_enqueue_scripts','childtheme_style_andscripts');
function form_action_function() {
require_once(dirname( __FILE__ ).'/../../../wp-load.php');
$data = $_POST['data'];
global $wpdb;
if( !check_ajax_referer('our-nonce', 'security' ) ) {
wp_send_json_error('security failed');
return;
}
//var_dump($data);
$rname=$data['rname'];
$ractive=$data['ractive'];
$table_name = "rituals";
$wpdb->insert($table_name, array ('Ritual_Name' => $rname, 'Ritual_Active' => $ractive) );
//$wpdb->show_errors();
//$wpdb->print_error();
echo 'From Submitted Successfully';
die();
}
add_action('wp_ajax_nopriv_form_action_function','form_action_function');
add_action('wp_ajax_form_action_function','form_action_function');
ajaxfunction.js
jQuery(document).ready(function($){
var submitButton = document.getElementById('usersubmit');
var ajaxFunctionformprocess = function(fromdata, action){
$.ajax({
type:'post',
url: usersubmitform.url,
data:{
action:action,
data:fromdata,
security:usersubmitform.security,
},
success:function(reponse){
$('div.msg').html(reponse);
},
error:function(response){
alert(response);
}
});
}
submitButton.addEventListener('click', function(event){
event.preventDefault();
var fromdata = {
'rname':document.getElementById('rname').value,
'ractive':document.getElementById('ractive').value,
};
ajaxFunctionformprocess(fromdata, 'form_action_function');
});
});
Samplepage.php(custom template)
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<h1 class="headingform">User Form</h1>
<div class="msg"></div>
<form class="userform">
Ritual Name: <input type="text" id="rname" name="rname" /><br> <br>
Ritual Active: <input type="text" id="ractive" name="ractive" /> <br><br>
<input id="usersubmit"type="submit" Value="Submit" />
</form>
</div><!-- #content -->
</div><!-- #primary -->
Case 1 :Create a template for display information from table
<?php
/*
Template Name: Disply Ritural
Description: display ritual information in table formate
*/
global $wpdb;
$table_name = "rituals";
$result = $wpdb->get_results ("SELECT * FROM $table_name");
foreach ( $result as $ritual_info )
{
echo $ritual_info['Ritual_Name'];
echo $ritual_info['Ritual_Active'];
}
Case 2 :Create a shortcode make it easy to use.open your functions.php file add code there.
function show_ritual_info(){
global $wpdb;
$table_name = "rituals";
$query="SELECT * FROM $table_name";
$result = $wpdb->get_results ($query);
foreach ( $result as $ritual_info )
{
echo $ritual_info['Ritual_Name'];
echo $ritual_info['Ritual_Active'];
}
}
add_shortcode('show_ritual_info','show_ritual_info');
How to use shortcode
Inside php file
<?php echo do_shortcode('[show_ritual_info]'); ?>
Inside admin page
['show_ritual_info']
Something like this:
<?php
global $wpdb;
$table_name = "rituals";
// this will get the data from your table
$retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name" );
?>
<?php if( ! empty($retrieve_data) ):?>
<table>
<tr>
<th>Ritual Name</th>
<th>Ritual Active</th>
</tr>
<?php foreach ($retrieve_data as $retrieved_data): ?>
<tr>
<td><?php echo $retrieved_data['Ritual_Name'];?></td>
<td><?php echo $retrieved_data['Ritual_Active'];?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
Not check but must work.)
Related
I have a nice demo importer which is working fine but with a category post count issue so there is plugin which is fixing this and I'm trying to integrate into my demo importer library.
This plugin here is fixing the issue after demo import but requires to go into the plugin page selecting post types in order to click on submit button.
Well this is the plugin admin page:
<?php
if($_POST) {
if(!check_admin_referer('select_post_types_'.get_current_user_id() )){
echo 'That is not allowed'; exit;
}
$fixes = $_POST['fix'];
foreach($fixes AS $fix_id){
$fix = new Fix_Category_Count();
$fix->post_type = $fix_id;
if($fix->process()){
$updated = TRUE;
}
}
}
?>
<div>
<?php echo "<h2>" . __( 'Fix Category Count Settings', 'fix_category_count' ) . "</h2>"; ?>
<h3>Select Post Types to Fix</h3>
<form name="site_data_form" method="post" action="<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ?>">
<div class="sa_block">
<?php
$post_types = get_post_types(array('public'=>TRUE));
foreach($post_types AS $post_type){
?>
<input type="checkbox" class="post_type" name="fix[]" id="fix_<?=$post_type; ?>" value="<?=$post_type; ?>" /> <label for="fix_<?=$post_type; ?>"><?=ucwords(preg_replace("/_/"," ",$post_type)); ?> (<?=$post_type;?>)</label><br />
<?php
}
?>
<br><br>
Select All |
Deselect All
</div>
</div>
<?php wp_nonce_field('select_post_types_'.get_current_user_id()); ?>
<div class="submit">
<input type="submit" name="Submit" value="<?php _e('Fix Categories Now', '' ) ?>" />
</div>
<?php if($updated){ ?>
<div class="updated"><p><strong><?php _e('Categories Updated.' ); ?></strong></p></div>
<? } ?>
</form>
</div>
<script type="text/javascript">
if(jQuery){
jQuery(document).ready(function($){
$('.select_boxes').click(function(e){
e.preventDefault();
if($(this).attr('rel')=='all'){
$('.post_type').each(function() {
this.checked = true;
});
}
else{
$('.post_type').each(function() {
this.checked = false;
});
}
});
});
}
</script>
So the CLASS of the plugin is here
I want to use only the class without the admin page with something like this:
ob_start();
if ( 'complete' == $response['process'] ) {
// Set imported menus to registered theme locations
$locations = get_theme_mod( 'nav_menu_locations' ); // registered menu locations in theme
$menus = wp_get_nav_menus(); // registered menus
if ( $menus ) {
foreach( $menus as $menu ) { // assign menus to theme locations
if( 'Main Menu' == $menu->name ) {
$locations['primary'] = $menu->term_id;
break;
}
}
}
set_theme_mod( 'nav_menu_locations', $locations ); // set menus to locations
global $wp_rewrite;
$wp_rewrite->set_permalink_structure('/%postname%/');
$wp_rewrite->flush_rules();
// I want to add the plugin functionality as a last process here!
}
ob_end_clean();
I'm not a php developer yet but I would like to get this working without fixing the category count using the plugin page options but directly on the function above and with the php class provided by plugin.
Thank you.
develope plugin,but while I am click on admin menu work and admin page open but when I click in page anchor link its not working give error(attachement).
Code forntend :
<?php
/**
*Plugin Name: my name
*Plugin URI: url for ref
*Description: my desciop
*Version:1.0.0.0
*Author:xyz
**/
function ShareEmbed()
{
global $current_user;
$user_ID = get_current_user_id();
global $wpdb;
$user_guid = $wpdb->get_results("SELECT wp_guid FROM wp_users where id=".$user_ID);
print_r($user_guid);
?>
<div class="wrapper">
<div class="blog-embed">
<span><h3>Code for share</h3></span>
<textarea readonly=""><a href='example.com?bloggerrefid='><img src='example.com/wp-content/uploads/2016/04/logo.png' alt='logo' width='' border='0'></a></textarea>
</div>
<div class="blog-embed-help">
<h3>How to configure afflication program?</h3>
<ul>
<li><b>Step-1:</b>login into your blog/website account.</li>
<li><b>Step-2:</b>copy above embed code</li>
<li><b>Step-3:</b>Paste code into your site area as html block</li>
<li><b>Step-4:</b>Save changes.</li>
<li><b>Step-5:</b>That's it.We are done with this.Once any one click on this link it consider as a hit.</li>
</ul>
</div>
</div>
<?php
}
add_shortcode('shareblog','ShareEmbed');
/**
* Register a custom menu page.
*/
function wpdocs_register_my_custom_menu_page() {
add_menu_page(
__( 'Custom Menu Title', 'textdomain' ),
'ShareThis',
'manage_options',
'wp-blogger-share-this/wp-blogger-share-this-admin.php',
'',
'dashicons-networking', 6
);
}
add_action( 'admin_menu', 'wpdocs_register_my_custom_menu_page' );
Admin file :
<?php
global $wpdb;
$current_guid=null;
$user_guids = $wpdb->get_results("SELECT DISTINCT wp_guid FROM wp_blogger_data");
?><table border=1 width="100%">
<tr><th width='30%'>User Name</th> <th width='30%'>Total Hits</th> <th width='30%'>Unique Hits</th><TH>-</TH>?</tr>
<?php
foreach ($user_guids as $user_guid) {
$username_by_GUID = $wpdb->get_row("SELECT `user_login` FROM `users` where `wp_guid` = '$user_guid->wp_guid'");
$unique_hits = $wpdb->get_row("SELECT COUNT(DISTINCT `ip_address`) AS `unique_hits` FROM `tb1` where `wp_guid`='$user_guid->wp_guid'");
$total_hits = $wpdb->get_row("SELECT COUNT(`ip_address`) AS `total_hits` FROM `tb1` where `wp_guid` = '$user_guid->wp_guid'");
?>
<tr><td><?php echo $username_by_GUID->user_login;?></td>
<?php
echo "<td>".$total_hits->total_hits."</td>";
echo "<td>".$unique_hits->unique_hits."</td>";
///wp-admin/admin.php?page=
wp-detail-view.php?id=wp_guid;
?>
">Delete
?>
Page here problem,I want to navigate on this page for details view.
wp-detail-view.php
<?php
echo "You are on Details view";
Here we need to include page inside main page and depend on query string.include files and output.
<?php
if(!isset($_GET['blogerid'])){
global $wpdb;
$current_guid=null;
$user_guids = $wpdb->get_results("SELECT DISTINCT wp_guid FROM wp_blogger_data");
?><table border=1 width="100%">
<tr><th width='30%'>User Name</th> <th width='30%'>Total Hits</th> <th width='30%'>Unique Hits</th></tr>
<?php
foreach ($user_guids as $user_guid) {
$username_by_GUID = $wpdb->get_row("SELECT `ID`,`user_login` FROM `wp_users` where `wp_guid` = '$user_guid->wp_guid'");
$unique_hits = $wpdb->get_row("SELECT COUNT(DISTINCT `ip_address`) AS `unique_hits` FROM `wp_blogger_data` where `wp_guid`='$user_guid->wp_guid'");
$total_hits = $wpdb->get_row("SELECT COUNT(`ip_address`) AS `total_hits` FROM `wp_blogger_data` where `wp_guid` = '$user_guid->wp_guid'");
?>
<tr><td><?php echo $username_by_GUID->user_login;?></td>
<?php
echo "<td>".$total_hits->total_hits."</td>";
echo "<td>".$unique_hits->unique_hits."</td>";
///wp-admin/admin.php?page=wp-blogger-detail-view.php?id=<?php echo $user_guid->wp_guid;
?>
<td>Delete</td>
<?php
}
?>
</table>
<?php
}
else
{
include 'wp-blogger-detail-view.php';
}
I am developing a wordpress plugin to allow users to submit a post from the frontend.
I have added a validation method and it works. How do I implement ajax validation in my code?
<?php
function exclutips_fep($content = null) {
global $post;
ob_start();
?>
<style>
#fep-new-post label{display:inline-block;width:15%;}
#fep-post-title input{width:60%;}
#fep-new-post input[type="submit"]{margin-left:15%;width:30%;padding:7px;}
#fep-new-post textarea{ display:inline-block;width:80%;vertical-align:top;}
</style>
<div id="exclutips-fep-postbox" class="<?php if(is_user_logged_in()) echo 'closed'; else echo 'loggedout'?>">
<?php do_action( 'exclutips-fep-notice' ); ?>
<div class="exclutips-fep-inputarea">
<?php if(is_user_logged_in()) { ?>
<form id="fep-new-post" name="new_post" method="post" action="<?php the_permalink(); ?>">
<p><label>Post Title *</label><input type="text" id ="fep-post-title" name="post-title" /></p>
<p>
<?php
$settings = array(
'textarea_rows' => 14,
'teeny' => true,
'quicktags' => false,
'textarea_name' => 'post-content',
'media_buttons' => true,
'editor_class' => 'front-end-post',
'tinymce' => array(
'theme_advanced_buttons1' => 'formatselect,|,bold,italic,underline,|,' .
'bullist,blockquote,|,justifyleft,justifycenter' .
',justifyright,justifyfull,|,link,unlink,|' .
',spellchecker,wp_fullscreen,wp_adv'
)
);
wp_editor( '', 'content', $settings);
?>
</p>
<p><label>Category</label>
<select name="post-category">
<option value=""><?php echo esc_attr_e( 'Select Category', 'exclutips-fep' ); ?></option>
<?php
$args = array(
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
printf( '<option value="%1$s">%2$s</option>',
esc_attr( '/category/archives/' . $category->category_nicename ),
esc_html( $category->cat_name )
);
}
?>
</select>
</p>
<p><label>Tags</label><input id="fep-tags" name="tags" type="text" tabindex="2" autocomplete="off" value="<?php esc_attr_e( 'Add tags', 'exclutips-fep' ); ?>" onfocus="this.value=(this.value=='<?php echo esc_js( __( 'Add tags', 'exclutips-fep' ) ); ?>') ? '' : this.value;" onblur="this.value=(this.value=='') ? '<?php echo esc_js( __( 'Add tags', 'exclutips-fep' ) ); ?>' : this.value;" /></p>
<input id="submit" type="submit" tabindex="3" value="<?php esc_attr_e( 'Post', 'exclutips-fep' ); ?>" />
<input type="hidden" name="action" value="post" />
<input type="hidden" name="empty-description" id="empty-description" value="1"/>
<?php wp_nonce_field( 'new-post' ); ?>
</form>
<?php } else { ?>
<h4 class="exclutips-fep-error">Please Log-in To Post</h4>
<?php } ?>
</div>
</div> <!-- #exclutips-fep-postbox -->
<?php
// Output the content.
$output = ob_get_contents();
ob_end_clean();
// return only if we're inside a page. This won't list anything on a post or archive page.
if (is_page()) return $output;
}
// Add the shortcode to WordPress. [exclutips-fep]
add_shortcode('exclutips-fep', 'exclutips_fep');
function exclutips_fep_errors(){
?>
<style>
.exclutips-fep-error{border:1px solid #CC0000;border-radius:5px;background-color: #FFEBE8;margin: 0 0 16px 0px;padding: 12px;}
</style>
<?php
global $error_array;
foreach($error_array as $error){
echo '<p class="exclutips-fep-error">' . $error . '</p>';
}
}
function exclutips_fep_notices(){
?>
<style>
.exclutips-fep-notice{ border:1px solid #E6DB55;border-radius:5px;background-color: #FFFBCC;margin: 0 0 16px 0px;padding: 12px;}
</style>
<?php
global $notice_array;
foreach($notice_array as $notice){
echo '<p class="exclutips-fep-notice">' . $notice . '</p>';
}
}
function exclutips_fep_add_post(){
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'post' ){
if ( !is_user_logged_in() )
return;
global $current_user;
$user_id = $current_user->ID;
$post_title = $_POST['post-title'];
$post_content = $_POST['post-content'];
$post_category = $_POST['post-category'];
$tags = $_POST['tags'];
global $error_array;
$error_array = array();
if (empty($post_title)) $error_array[]='Please add a post title.';
if (empty($post_content)) $error_array[]='Please add some content.';
if (empty($post_category)) $error_array[]='Please select category.';
if (count($error_array) == 0){
$post_id = wp_insert_post( array(
'post_author' => $user_id,
'post_title' => $post_title,
'post_type' => 'post',
'post_content' => $post_content,
'post_category' => $post_category,
'tags_input' => $tags,
'post_status' => 'publish'
) );
global $notice_array;
$notice_array = array();
$notice_array[] = "Thank you for posting. Your post is now live. ";
add_action('exclutips-fep-notice', 'exclutips_fep_notices');
} else {
add_action('exclutips-fep-notice', 'exclutips_fep_errors');
}
}
}
add_action('init','exclutips_fep_add_post');
Please try it.. it is works for me.
1) call this on click of your button.. (it is the code of your lending page)
var pathname = window.location.pathname;
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
var email = $('#email').val();
var phoneNumber = $('#phoneNumber').val();
var data = new Array (firstName,lastName,email,phoneNumber);
$.get( ajax_request_url,
{
'action' : 'get_myusers',
'data' : data,
'pathname' : pathname
},
function( response )
{
$('.displayUsers').html(response);
$('#myForm')[0].reset();
$('.addForm').hide();
$('.displayAddForm').show();
$('.hideAddForm').hide();
}, "html" );
2) this is functions.php code
/* custom function for display user
* using ajax user add update delete
*/
add_action('wp_footer', 'eps_footer');
function eps_footer() {
echo "<script>var ajax_request_url = '".admin_url( 'admin-ajax.php' )."'</script>";
}
//Get user Ajax
add_action( 'wp_ajax_nopriv_get_myusers', 'get_myusers' );
add_action( 'wp_ajax_get_myusers', 'get_myusers' );
function get_myusers()
{
$userArray = $_REQUEST['data'];
$table = "my_table";
$data = array(firstName=>$userArray[0],lastName=>$userArray[1],email=>$userArray[2],foneNumber=>$userArray[3]);
global $wpdb;
$wpdb->insert( $table, $data );
?>
<table>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone Number</th>
<th>Action</th>
</tr>
<?php
$users = $wpdb->get_results( "SELECT * FROM my_table" );
foreach($users as $user)
{
?>
<tr id="displayTr<?php echo $user->my_table_id;?>">
<td><?php echo $user->firstName; ?></td>
<td><?php echo $user->lastName; ?></td>
<td><?php echo $user->email; ?></td>
<td><?php echo $user->foneNumber; ?></td>
<td>
Delete
Edit
</td>
</tr>
<tr style="display:none;" class="editTr" id="editTr<?php echo $user->my_table_id;?>">
<td><input type="text" id="firstName<?php echo $user->my_table_id;?>" value="<?php echo $user->firstName; ?>"></td>
<td><input type="text" id="lastName<?php echo $user->my_table_id;?>" value="<?php echo $user->lastName; ?>"></td>
<td><input type="text" id="email<?php echo $user->my_table_id;?>" value="<?php echo $user->email; ?>"></td>
<td><input type="text" id="phoneNumber<?php echo $user->my_table_id;?>" value="<?php echo $user->foneNumber; ?>"></td>
<td>
Update
Cancle
</td>
</tr>
<?php
}
?>
</table>
<?php
}
die();
You can do like some steps below:
Step 1: Localize WP Ajax URL
<?php
add_action('wp_head','pluginname_ajaxurl');
function pluginname_ajaxurl() { ?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
Step 2: Send your post information by using ajax
$.ajax({
type: 'post',
url: ajaxurl ,
data: {
action: 'validation',
data: [yourdata]
},
beforeSend: function() {},
success: function(resp) {
}
});
Step 3: Receive data on PHP server by using WP Hook
<?php
// this action will run for loged in user
add_action('wp_ajax_validation', 'exclutips_fep_add_post');
// This action will run for visitor
add_action('wp_ajax_wp_ajax_nopriv_validation', 'exclutips_fep_add_post');?>
Hope Those can help you solve your problem.
Your question is a bit open ended. But one important piece of security validation is implementing nonces. This checks the ajax request is coming from your site as intended, which prevents a variety of attacks.
In your php you create a nonce and pass it into the javascript as a variable.
wp_register_script( 'your-script', /*file url here*/ , /*dependencies here*/, false, false);
$params = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce('name-the-nonce'),
);
wp_localize_script( 'your-script', 'jsParameters', $params );
wp_enqueue_script( 'your-script' );
In your javascript you pass the nonce to the php like so:
var ajaxRequest = $.post(
jsParameters.ajaxurl,
{
action: 'your_action',
// send the nonce along with the request
nonce: jsParameters.nonce
},
function (response) {
//some reponse code
}
);
Within the AJAX php function you perform this validation:
$nonce = $_POST['nonce'];
if (!wp_verify_nonce($nonce, 'name-the-nonce'))
die('Busted');
//continue executing ajax php code
Some external material on the matter:
https://codex.wordpress.org/WordPress_Nonces
http://www.barrykooij.com/check-nonces-wordpress-ajax-calls/
Hi expert wp plugin developers, I need help. I have apply bellow code but not working default value and not showing updated notification after clicking save button. When I put all value in option page from dashboard everything is ok. But not showing all updated notification. Please help me.
<?php
function hkhk_options() {
add_menu_page('Scrol Line Admin Settings', 'hk Settings','manage_options',
'hk_settings', 'hk_admin_options');
}
add_action('admin_menu', 'hkhk_options');
function hk_defaults()
{
$hk_options = array(
'back_color' => '#ccc',
);
}
if ( is_admin() ) :
function hk_register_settings () {
register_setting('hkhk_options', 'hk_options', 'hk_validate_options');
}
add_action('admin_init', 'hk_register_settings');
function hk_admin_options() {
global $hk_options;
if ( ! isset( $_REQUEST['updated'] ) )
$_REQUEST['updated'] = false;
?>
<div class="wrap">
<h2>Select Scrol Line Option</h2>
<?php if ( false !== $_REQUEST['updated'] ) : ?>
<div class="update fade"><p><strong><?php _e( 'Options saved' ); ?></strong></p></div>
<?php endif; // If the form has just been submitted, this shows the notification ?>
<form method="post" action="options.php">
<?php $settings=get_option ( 'hk_options', $hk_options ); ?>
<?php settings_fields('hkhk_options'); ?>
<table class="form-table">
<tr valign="top">
<th scope="row"><label for="back_color"> Back Color </label></th>
<td>
<input id="back_color" type="text" name="hk_options[back_color]" value="<?php esc_attr_e($settings['back_color']); ?>" class="wp-picker-container" /><p class="description"> Choose any color from here for background color. </p>
</td>
</tr>
</table>
<p class="submit"><input type="submit" class="button-primary" value="Save Options" /> </p>
</form>
</div>
<?php
}
function hk_validate_options( $input ){
global $hk_options;
$settings = get_option( 'hk_options', $hk_options );
$input['back_color'] = wp_filter_post_kses( $input['back_color'] );
return $input;
}
endif;
function scrol_line_active() {?>
<?php global $hk_options; $hk_settings = get_option ( 'hk_options', $hk_options ); ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
jQuery("body") .hk({
backColor: "<?php echo $hk_settings['back_color']; ?>",
});
});
</script>
<?php
}
add_action ('wp_head', 'scrol_line_active');
?>
You are checking wrong REQUEST parameter. You need to check $_REQUEST['settings-updated'].
When option page is submitted new URL is similar to /wp-admin/admin.php?page=hk_settings&settings-updated=true.
Hope this helps.
I'm two or three weeks old to Wordpress, I'm writing a tiny custom system as a plugin for a wordpress-based site. This systems reads a set of json encoded files and shows them as a table list.
Together with some basic settings that I'm already saving, I want to include a simple text editor for these json files, and I was wondering if there's a way to 'attach' a custom action for the options.php script that processes form submission, in order to send to it the file path and content.
I'm currently thinking in writing some ajax, but I prefer to ask here before, maybe there is a simple way to achieve this.
myplugin.php
function myplugins_menu(){
add_options_page('myplugin configuration','myplugin','manage_options', _
'myplugin_menu','myplugin_options');
//call register settings function
add_action( 'admin_init', 'register_mysettings' );
}
add_action('admin_menu','myplugin_menu');
function myplugin_options(){
include('admin/myplugin-admin.php');
}
function register_mysettings() {
//register our settings
$setting_list=array('mail_title','mail_from','mail_to','recipient');
foreach ($setting_list as $setting){
register_setting( 'myplugin-settings-group', $setting );
}
}
myplugin-admin.php
<div class="wrap">
<h2>My plugin</h2>
<h3>My plugin Options</h3>
<form method="post" action="options.php">
<?php settings_fields( 'myplugin-settings-group' ); ?>
<?php do_settings_sections( 'myplugin-settings-group' ); ?>
<table class="form-table">
<?php
print_option('Mail Subject','mail_title');
print_option('Sender address','mail_from');
print_option('Recipient address','mail_to');
print_option('Recipient name','recipient');
?>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
echo "<select name=\"filename\" size=\"1\">";
$dir = plugin_dir_path( __FILE__ );
$files = glob($dir."../services/*.json");
foreach ($files as $filename){
echo "<option value=\"".basename($filename)."\">".basename($filename)."</option>";
}
echo "</select>";
$dir = plugin_dir_path( __FILE__ );
$file = file(WP_PLUGIN_DIR."/myplugin/services/010.Luftansa.json");
echo "<form action=\"".$_SERVER['PHP_SELF']."\" method=\"post\">";
echo "<textarea Name=\"update\" cols=\"50\" rows=\"10\">";
foreach($file as $text) {
echo $text;
}
echo "</textarea>";
echo "<input name=\"Submit\" type=\"submit\" value=\"Update\" />\n
</form>";
}
In the snippet above,
I put _SERVER['PHP_SELF'] as the action for the form, but this turns into /wp/wp-admin/options-general.php;.
If I put a path to my admin file I can't return to the admin interface except by an http-refresh or something like that.
Thanks for reading :)
myplugin-admin.php
<?php
/**
* #package my_plugin
* #version 1.6
*/
/*
Plugin Name: my plugin
Plugin URI:
Description:
Author:
Version:
Author URI:
*/
include_once(WP_PLUGIN_DIR."/my_plugin/model.php");
function my_plugin_admin_scripts(){
?>
<script type='text/javascript'>
jQuery('select')
.change(function() {
var filename = '';
jQuery('select option:selected').each(function() {
filename += jQuery( this ).text() + ' ';
});
jQuery.ajax({
type: 'GET',
url: '<?php echo WP_PLUGIN_URL;?>/my_plugin/action.php',
data: 'action=' + 'getJsonFile'+'&file='+filename,
success: function(data) {
jQuery('#services_file').val(data);
},
error: function(data) {
jQuery('#services_file').val('Something went wrong while loading '+filename+' file content');
}
});
})
.trigger('change');
</script>
<?php
}
add_action( 'admin_footer', 'my_plugin_admin_scripts' );
function print_option($label,$opt_name){
$str = "
<tr valign=\"top\">
<th scope=\"row\">{$label}</th>
<td><input type=\"text\" name=\"{$opt_name}\" value=\"".get_option($opt_name)."\" /></td>
</tr>";
echo $str;
}
function my_plugin_admin_tabs( $current = 'general' ) {
$tabs = array( 'general' => 'General', 'services' => 'Services');
echo "<h3>My plugin Options</h3>";
echo '<div id="icon-themes" class="icon32"><br></div>';
echo '<h2 class="nav-tab-wrapper">';
foreach( $tabs as $tab => $name ){
$class = ( $tab == $current ) ? ' nav-tab-active' : '';
echo "<a class='nav-tab$class' href='?page=my_plugin_menu&tab=$tab'>$name</a>";
}
echo '</h2>';
}
function tab_content_general() {
?>
<form method="post" action="options.php">
<?php settings_fields( 'my_plugin-settings-group' ); ?>
<?php do_settings_sections( 'my_plugin-settings-group' ); ?>
<table class="form-table">
<?php
print_option('Mail Subject','mail_title');
print_option('Sender address','mail_from');
print_option('Recipient address','mail_to');
print_option('Recipient name','recipient');
?>
</table>
<?php submit_button(); ?>
</form>
<?php
}
function tab_content_services(){
$files = glob(WP_PLUGIN_DIR."/my_plugin/services/*.json");
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?page=my_plugin_menu&tab=services">
<table class="form-table">
<tr><td><select name="filename" size="1" style="width: 180px">
<?php
foreach ($files as $filename){
echo "<option value=\"".basename($filename)."\">".basename($filename)."</option>";
}
?>
</select>
<input name="Submit" type="submit" value="Update" />
</td></tr>
<tr><td><textarea id="services_file" name="update" cols="80" rows="18" style="font-family: monospace">
</textarea></td></tr>
</table>
</form>
<?php
}
$tab = ( isset ( $_GET['tab'] ) )?$_GET['tab']:"general";
my_plugin_admin_tabs($tab);
?>
<div class="wrap">
<?php
switch ($tab) {
case "general":
tab_content_general();
break;
case "services":
tab_content_services();
break;
default:
break;
}
?>
</div>
<?php
if($_POST['Submit']){
save_json_file($_POST['filename'],$_POST['update']);
}
?>
action.php
<?php
define( 'WP_USE_THEMES', false );
require_once( '../../../wp-load.php' );
require_once('model.php');
//main
if (isset($_GET['action'])){
$action = $_GET['action'];
}
if (isset($_POST['action'])){
$action = $_POST['action'];
}
if (isset($action)) {
switch ($action){
case 'getJsonFile':
getJsonFile($_GET['file']);
break;
default:
echo "action unknown";
break;
}
}
?>
model.php
<?php
function isJson($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
function read_plain_json($file){
$file = file(WP_PLUGIN_DIR."/my_plugin/services/".$file);
return implode("",$file);
}
function getJsonFile($file){
echo read_plain_json($file);
die();
}
function save_json_file($file,$content){
$open = fopen(WP_PLUGIN_DIR."/my_plugin/services/".$file,"w+");
fwrite($open, stripslashes($content));
fclose($open);
}
?>
my_plugin/services/010.Luftansa.json
[
{
"subcat": "Natural Nail Care",
"column": ["service","Mani","Pedi","Mani & Pedi","info","book"],
"service": [
["Deluxe","40.00","55.00","90.00","Service Information","Book Deluxe"],
["Express","30.00","45.00","71.00","","BookExpress"],
["Fully Loaded","55","70","119.00","ServiceInformation","Book Fully Loaded"],
["French","45","60","100.00","","Book French"],
["Pure and Natural","50","60","105.00","Service Information","Book Pure And Natural"],
["Deluxe Series of 6","216","297","487.00","","Book Deluxe Series Of 6"],
["Re-varnish and Tidy-up Hands","18","20","35","","Book Re-Varnish And Tidy-Up Hands"],
["Course of 6","","","","","Book Course Of 6"]
]
}