How to call a php class in wordpress? - php

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.

Related

Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?

i iclude a wordpress media selector in my wordpress plugin.
i got this error :
Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?
error
i added to this code to wp-config.php file :
`
/** WordPress değişkenlerini ve yollarını kurar. */
require_once ABSPATH . 'wp-settings.php';
define( 'UPLOADS', 'wp-content/uploads' );
`
and added to myportfolio-form.php file
<?php
add_action( 'admin_footer', 'media_selector_print_scripts' );
function media_selector_print_scripts() {
$my_saved_attachment_post_id = get_option( 'media_selector_attachment_id', 0 );
?><script type='text/javascript'>
jQuery( document ).ready( function( $ ) {
// Uploading files
var file_frame;
var wp_media_post_id = wp.media.model.settings.post.id; // Store the old id
var set_to_post_id = <?php echo $my_saved_attachment_post_id; ?>; // Set this
jQuery('#upload_image_button').on('click', function( event ){
event.preventDefault();
// If the media frame already exists, reopen it.
if ( file_frame ) {
// Set the post ID to what we want
file_frame.uploader.uploader.param( 'post_id', set_to_post_id );
// Open frame
file_frame.open();
return;
} else {
// Set the wp.media post id so the uploader grabs the ID we want when initialised
wp.media.model.settings.post.id = set_to_post_id;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: 'Select a image to upload',
button: {
text: 'Use this image',
},
multiple: false // Set to true to allow multiple files to be selected
});
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
// We set multiple to false so only get one image from the uploader
attachment = file_frame.state().get('selection').first().toJSON();
// Do something with attachment.id and/or attachment.url here
$( '#image-preview' ).attr( 'src', attachment.url ).css( 'width', 'auto' );
$( '#image_attachment_id' ).val( attachment.id );
// Restore the main post ID
wp.media.model.settings.post.id = wp_media_post_id;
});
// Finally, open the modal
file_frame.open();
});
// Restore the main ID when the add media button is pressed
jQuery( 'a.add_media' ).on( 'click', function() {
wp.media.model.settings.post.id = wp_media_post_id;
});
});
</script><?php
}
function portfolio_admin_myprojects_page_handler()
{
global $wpdb;
$table = new Portfolio_MyProjects_List_Table();
$table->prepare_items();
$message = '';
if ('delete' === $table->current_action()) {
$message = '<div class="updated below-h2" id="message"><p>' . sprintf(__('Items deleted: %d', 'portfolio-admin-myresume'), count($_REQUEST['ID'])) . '</p></div>';
}
?>
<div class="wrap">
<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
<h2><?php _e('My Projects', 'portfolio-admin-myresume')?> <a class="add-new-h2"
href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=myprojects_form');?>"><?php _e('Add new', 'portfolio-admin-myresume')?></a>
</h2>
<?php echo $message; ?>
<form id="myprojects-table" method="POST">
<input type="hidden" name="page" value="<?php echo $_REQUEST['page'] ?>"/>
<?php $table->display() ?>
</form>
</div>
<?php
}
function portfolio_admin_projects_form_page_handler()
{
global $wpdb;
$table_name = $wpdb->prefix . 'portfolio_myprojects';
$message = '';
$notice = '';
$default = array(
'ID' => 0,
'projects_name' => '',
'projects_category' => '',
'projects_link' => '',
'projects_image' => '',
'order' => '',
);
if ( isset($_REQUEST['nonce']) && wp_verify_nonce($_REQUEST['nonce'], basename(__FILE__))) {
$item = shortcode_atts($default, $_REQUEST);
$item_valid = portfolio_admin_validate_myprojects($item);
if ($item_valid === true) {
if ($item['ID'] == 0) {
$result = $wpdb->insert($table_name, $item);
$item['ID'] = $wpdb->insert_id;
if ($result) {
$message = __('Item was successfully saved', 'portfolio-admin-myresume');
} else {
$notice = __('There was an error while saving item', 'portfolio-admin-myresume');
}
} else {
$result = $wpdb->update($table_name, $item, array('ID' => $item['ID']));
if ($result) {
$message = __('Item was successfully updated', 'portfolio-admin-myresume');
} else {
$notice = __('There was an error while updating item', 'portfolio-admin-myresume');
}
}
} else {
$notice = $item_valid;
}
}
else {
$item = $default;
if (isset($_REQUEST['ID'])) {
$item = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table_name WHERE ID = %d", $_REQUEST['ID']), ARRAY_A);
if (!$item) {
$item = $default;
$notice = __('Item not found', 'portfolio-admin-myresume');
}
}
}
add_meta_box('myprojects_form_meta_box', __('Work Details', 'portfolio-admin-myresume'), 'portfolio_admin_projects_form_meta_box_handler', 'myprojects', 'normal', 'default');
?>
<div class="wrap">
<div class="icon32 icon32-posts-post" id="icon-edit"><br></div>
<h2><?php _e('My Projects', 'portfolio-admin-myresume')?> <a class="add-new-h2"
href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page=myprojects');?>"><?php _e('back to list', 'portfolio-admin-myresume')?></a>
</h2>
<?php if (!empty($notice)): ?>
<div id="notice" class="error"><p><?php echo $notice ?></p></div>
<?php endif;?>
<?php if (!empty($message)): ?>
<div id="message" class="updated"><p><?php echo $message ?></p></div>
<?php endif;?>
<form id="form" method="POST">
<input type="hidden" name="nonce" value="<?php echo wp_create_nonce(basename(__FILE__))?>"/>
<input type="hidden" name="ID" value="<?php echo $item['ID'] ?>"/>
<div class="metabox-holder" id="poststuff">
<div id="post-body">
<div id="post-body-content">
<?php do_meta_boxes('myprojects', 'normal', $item); ?>
<input type="submit" value="<?php _e('Save', 'portfolio-admin-myresume')?>" id="submit" class="button-primary" name="submit">
</div>
</div>
</div>
</form>
</div>
<?php
}
function portfolio_admin_projects_form_meta_box_handler($item)
{
// Save attachment ID
if ( isset( $_POST['submit_image_selector'] ) && isset( $_POST['image_attachment_id'] ) ) :
update_option( 'media_selector_attachment_id', absint( $_POST['image_attachment_id'] ) );
endif;
wp_enqueue_media();
?>
<tbody >
<div class="formdatabc">
<form >
<div class="form2bc">
<p>
<label for="projects_name"><?php _e('Project Name:', 'portfolio-admin-myresume')?></label>
<br>
<input id="projects_name" name="projects_name" type="text" value="<?php echo esc_attr($item['projects_name'])?>"
required>
</p>
</div>
<div class="form2bc">
<p>
<label for="projects_category"><?php _e('Project Category', 'portfolio-admin-myresume')?></label>
<br>
<input id="projects_category" name="skills_percent" type="text" value="<?php echo esc_attr($item['projects_category'])?>"
required>
</p>
</div>
<div class="form3bc">
</div>
<div>
<p>
<label for="projects_link"><?php _e('Project Link:', 'portfolio-admin-myresume')?></label>
<br>
<textarea id="projects_link" name="projects_link" cols="100" rows="3" maxlength="240"><?php echo esc_attr($item['projects_link'])?></textarea>
</p>
</div>
<div class='image-preview-wrapper'>
<img id='image-preview' src='' width='100' height='100' style='max-height: 100px; width: 100px;'>
</div>
<input id="upload_image_button" type="button" class="button" value="<?php _e( 'Upload image' ); ?>" />
<input type='hidden' name='image_attachment_id' id='image_attachment_id' value=''>
</form>
</div>
</tbody>
<?php
}
`
i tried to iclude wordpress media selector to my plugin but it doesnt work.
error : Unable to create directory wp-content/uploads/2022/12. Is its parent directory writable by the server?
You need to change permissions of directories on server itself
chmod -R 777 /path/to/web-root/wp-content/uploads
(Linux example, this will change all files)
chmod 777 /path/to/web-root/wp-content
(this will change only directory itself, not all files)

Display the inserted data in wordpress custom template

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.)

Default option value not working automatically

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.

WordPress My theme options settings not saving

I just created a simple theme option page that is working fine and also saved after when press save options.
But when I go somewhere else from theme options page and come back to theme options page that settings what I saved just disappear and I have to change that again whenever I come to theme options page.
Here is my code
add_action( 'admin_menu', 'theme_options_add_page' );
if ( get_option('new_theme_options')) {
$theme_options = get_option('new_theme_options');
} else {
add_option('new_theme_options', array (
'sidebar2_on' => true,
'footer_text' => ''
));
$theme_options = get_option('new_theme_options');
}
function theme_options_add_page() {
add_submenu_page( 'themes.php', 'My Theme Options', 'Theme Options', 8, 'themeoptions', 'theme_options_do_page' );
}
function theme_options_do_page() {
global $theme_options;
$new_values = array (
'footer_text' => htmlentities($_POST['footer_text'], ENT_QUOTES),
);
update_option('new_theme_options', $new_values);
$theme_options = $new_values;
?>
<div class="wrap">
<?php screen_icon(); echo "<h2>" . get_current_theme() . __( ' Theme Options', 'responsivetheme' ) . "</h2>"; ?>
<form method="post" action="themes.php?page=themeoptions">
<label for="footer_text">Footer Text:</label>
<input id="footer_text" type="text" name="footer_text" value="<?php echo $theme_options['footer_text']; ?>" />
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e( 'Save Options', 'responsivetheme' ); ?>" />
</p>
</form>
</div>
<?php
}
#Praveen answer is correct, but for completeness I'll post the full code I tested. Please, note that you should always develop with WP_DEBUG enabled. It shows three issues with your code:
using $_POST['footer_text'] without it being defined (Praveen's answer)
using the deprecated function get_current_theme()
using Level instead of Capability in add_submenu_page()
I dropped the following code into my theme's functions.php and it works ok:
if ( get_option('new_theme_options')) {
$theme_options = get_option('new_theme_options');
} else {
$theme_options = array (
'sidebar2_on' => true,
'footer_text' => ''
);
add_option( 'new_theme_options', $theme_options );
}
add_action( 'admin_menu', 'theme_options_add_page' );
function theme_options_add_page() {
add_submenu_page(
'themes.php',
'My Theme Options',
'Theme Options',
'add_users',
'themeoptions',
'theme_options_do_page'
);
}
function theme_options_do_page() {
global $theme_options;
if( isset( $_POST['footer_text'] ) ) {
$new_values = array (
'footer_text' => htmlentities( $_POST['footer_text'], ENT_QUOTES),
);
update_option('new_theme_options', $new_values);
$theme_options = $new_values;
}
?>
<div class="wrap">
<?php screen_icon(); echo "<h2>" . wp_get_theme() . __( ' Theme Options', 'responsivetheme' ) . "</h2>"; ?>
<form method="post" action="themes.php?page=themeoptions">
<label for="footer_text">Footer Text:</label>
<input id="footer_text" type="text" name="footer_text" value="<?php echo $theme_options['footer_text']; ?>" />
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e( 'Save Options', 'responsivetheme' ); ?>" />
</p>
</form>
</div>
<?php
}
The only issue I can see is the option value sidebar2_on that's being overwritten in theme_options_do_page(), but your sample code does not show it being used elsewhere.
Please change this code:
if($_POST['footer_text']) {
$new_values = array (
'footer_text' => htmlentities($_POST['footer_text'], ENT_QUOTES),
);
update_option('new_theme_options', $new_values);
$theme_options = $new_values;
}
hope this will work fine :)

Editing Wordpress remote file within plugin settings page

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"]
]
}

Categories