Adding a Settings Field to my WP Sub Menu Page - php

Hello I'm currently following a guide on how to add input to my created Sub Menu Pages. Here is a pic of what is showing up. http://imgur.com/a/St9wj .When I view the sub-menu page. No Errors, just not showing the text field. The Function function mytheme_general_name() is not getting called in the 2nd add_submenu_page, but I don't see what is wrong with it.
I copied the Here is my Current two php files in use
File Name: function-admin.php
/*
#package Jeron
========================
ADMIN PAGE
========================
*/
function mytheme_add_theme_options() {
// Generate Theme Options Page
add_menu_page('My Themes Theme Options', 'Theme Options', 'manage_options', 'theme2_options', 'mytheme_create_page', get_template_directory_uri().'/img/themeoptionsicon.png', 110);
// Generate Theme Options Sub Pages
add_submenu_page('theme2_options', 'Theme Options', 'General', 'manage_options', 'theme2_options', 'mytheme_create_page');
add_submenu_page('theme2_options', 'Typography', 'Typography', 'manage_options', 'theme_options_typography', 'mytheme_create_typography_page');
}
add_action('admin_menu', 'mytheme_add_theme_options');
// Activate Custom Settings
add_action('admin_init', 'mytheme_custom_settings');
function mytheme_custom_settings() {
register_setting('mytheme-settings-group', 'first_name');
add_settings_section('mytheme-general-options', 'General Settings', 'mytheme_general_options', 'theme2_options');
add_settings_field('general-name', 'First Name', 'mytheme_general_name', 'theme2_options', 'mytheme_settings_group');
}
function mytheme_general_options() {
echo 'Customize Your Theme Options Below';
}
function mytheme_general_name() {
$firstName = esc_attr(get_option('first_name'));
echo '<input type="text" name="first_name" value="'.$firstName.'" placeholder="First Name" />';
}
function mytheme_create_page() {
require_once(get_template_directory().'/inc/templates/mytheme-admin.php');
}
function mytheme_create_typography_page() {
echo '<h1>My Theme Typography</h1>';
}
?>
File Name: mytheme-admin.php
<h1>My Theme Options</h1>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php settings_fields('mytheme_settings_group');?>
<?php do_settings_sections( 'theme2_options' ); ?>
<?php submit_button(); ?>
</form>

Related

how to use jquery in php without using external .js file in wordpress

I have created a datepicker for my wordpress admin menu. So far I implemented it with external js buy now I want to use jquery inside my plugin's php file itself. I don't want to declare in any external .js files. Please help me... I looked for the solutions in google but I am unable to understand as I am a beginner..
<?php
add_action( 'admin_menu', function()
{
$hook = add_menu_page(
'Date Pick',
'Date Pick',
'manage_options',
'sub-page-date-picker',
function() {
echo '<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">';
echo '<link rel="stylesheet" href="/resources/demos/style.css">';
echo '<script src="https://code.jquery.com/jquery-1.12.4.js"></script>';
echo '<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>';
echo '<form action="" method="post" id="dateform">';
echo '<h1>Date Pick</h1>';
echo '<div id="datepicker" class="datepickerclass"></div>';
echo '<div id="DatePickerHidden"></div>';
echo '<div id="feedback"></div>';
echo '<input type="submit" id="submitform" name="submit" value="submit">';
echo '</form>';
}
);
add_action( 'admin_enqueue_scripts', function( $hook )
{
if( 'toplevel_page_sub-page-date-picker' !== $hook )
return;
wp_enqueue_script(
'field-date-js',
plugins_url( '/ft.js', __FILE__ ),
array('jquery', 'jquery-ui-core', 'jquery-ui-datepicker'),
time(),
true
);
wp_enqueue_style('jquery-ui-datepicker');
});
});
wp_enqueue_script('jquery');
?>

Add logout link to WordPress admin dashboard left sidebar menu

I want to add logout link(button) in the left side of my wordpress admin dashboard. Like on the picture.. How can I do it?
UPDATED
You can achive this using admin_init action hook and global $menu.
Here is this code:
add_action('admin_init', 'text_domain_logout_link');
function text_domain_logout_link() {
global $menu;
$menu[9999] = array(__('Logout'), 'manage_options', wp_logout_url());
}
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
The code is tested and fully functional.
References:
admin_init
global $menu
Customizing Your WordPress Admin
Use following code
add_action('admin_menu', 'register_custom_menu_page');
function register_custom_menu_page() {
add_menu_page( 'admin_menu', 'Logout', '0', 'logout', 'users_add_login_logout_link');
}
function users_add_login_logout_link(){ ?>
<div id="dashboard" class="wrap">
<div style="float: left; height: 48px margin: 7px 8px 0 0; width: 48px;">
<br>
</div>
<h2>Log Out</h2>
</div>
<div style="text-align: center;"><img src="put you image link" width="128px" height="128px" /></div>
<div style="text-align: center;">Please wait we are logging you out ...</div>
<br/>
<br/>
<div style="padding: 10px 0; font-size: 25px;"><p>
</div>
<?php
$location = '"Location: ' . wp_logout_url() . '"';
echo '<meta http-equiv="refresh" content="4; url=' . wp_logout_url(home_url()) . '"/>';
}
Another alternative, with a dashicon. Based on this answer.
add_action('admin_menu', 'logout_menu_item');
function logout_menu_item() {
add_menu_page('', 'Logout', 'manage_options', 'logout', '__return_false', 'dashicons-external', 999);
}
add_action('after_setup_theme', 'redirect_loggingout');
function redirect_loggingout() {
if ( isset($_GET['page']) && $_GET['page'] == 'logout' ) {
wp_redirect( wp_logout_url() );
exit();
}
}

On AJAX call session is destroying WordPress plugin

I am calling an AJAX function from WordPress plugin through admin-ajax.php. But when the request is send, its destroying the session.
I have an array where data is saved on every request, but on every request previous data is destroyed.
AJAX code i am calling:
function cartbox()
{
var url = {
'action':'my_cart_action',
'rnd':Math.random(),
};
$.ajax({
type:'POST',
data:url,
url: "http://localhost/vmlogic/wp-admin/admin-ajax.php",
success : function(response)
{
$("#cartdiv").html(response);
}
});
}
On plugin index file i am calling this:
class cloud_calculator{
// Call a cation on link click
function cloud_calculator()
{
add_action('init' , array($this,'cloud_init'));
}
public function cloud_init()
{
add_action('wp_head' , array($this, 'plugin_jquery_func'));
add_action('admin_menu', array($this,'my_menu'));
add_shortcode('cloud_calculator', array($this,'my_calculator'));
add_action('the_content', array($this,'the_content_action'));
add_action( 'wp_ajax_my_unique_action', array($this,'my_unique_action_callback'));
add_action( 'wp_ajax_nopriv_my_unique_action', array($this,'my_unique_action_callback'));
add_action( 'wp_ajax_my_cart_action', array($this,'my_cart_action_callback'));
add_action( 'wp_ajax_nopriv_my_cart_action', array($this,'my_cart_action_callback'));
}
public function plugin_jquery_func()
{
$plugins_url = plugins_url().'/cloud-calculaor/';
?>
<script type="application/javascript">
var PluginUrlJs = '<?php echo $plugins_url ;?>';
</script>
<?php }
public function the_content_action($content)
{
$content = str_replace('[cloud_calculator]',do_shortcode('[cloud_calculator]') ,$content );
return $content;
}
// Menu call function
public function my_menu() {
add_menu_page('Cloud Calculator', 'Cloud Calculator', 'manage_options', 'cloud-calculaor/cloud-calculaor.php', array($this, 'my_function'));
}
// action to call on admin menu
public function my_function() {
wp_enqueue_style('style', '/wp-content/plugins/cloud-calculaor/style/admincalculator.css');
echo
'<div class="wrap">
<h2>Cloud Calculator</h2>
<div class="plugincode">
<div style=" padding:10px 10px 10px 50px;">
<p style="margin:5px 0px">
To Insert <strong>CLOUD CALCULATOR</strong> shortcode inside a page or post:<br>
<br>
Use: <code><strong>[cloud_calculator]</strong></code><br>
<br>
For more queries contact the administrator!<br>
</p>
</div>
</div>
</div>
';
}

Ajax not working in submit button

I am creating this wordpress plugin it works well but the issue here in subimt data using ajax. I already created the ajax code but it doesn't work.
Please help to figure it out
Thank You
Here is the code
<script>
var data = {
action: 'join_mailinglist',
email: email
};
jQuery("#mailinglistsubmit").hide();
jQuery(".ajaxsave").show();
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data,
function(response){
jQuery(".ajaxsave").hide();
jQuery("#mailinglistsubmit").show();
});
return false;
</script>
<?php
/*
Plugin Name: MyFirst
Plugin URI: http://zachis.it
Description: ajax form.
Version: 1.0
Author: Zachary Smith
Author URI: http://zachis.it
License: GPL2
*/
?>
<?php
/* What to do when the plugin is activated? */
register_activation_hook(__FILE__,'my_first_plugin_install');
/* What to do when the plugin is deactivated? */
register_deactivation_hook( __FILE__, 'my_first_plugin_remove' );
function my_first_plugin_install() {
/* Create a new database field */
add_option("my_first_data", 'Testing !! My Plugin is Working Fine.', 'This is my first plugin panel data.', 'yes');
}
function my_first_plugin_remove() {
/* Delete the database field */
delete_option('my_first_data');
}
add_action('admin_menu', 'my_first_admin_menu');
function my_first_admin_menu() {
add_options_page('Plugin Admin Options', 'My Plugin Settings', 'manage_options',
'my-first', 'plugin_admin_options_page');
}
?>
<?php
function plugin_admin_options_page() {
?>
<div class="wrap">
<?php screen_icon(); ?>
<h2>Plugin Options Admin Page</h2>
</div>
<div class="content">
<div class="output"><p><?php echo get_option('my_first_data'); ?></p></div>
<p>
<form method="post" action="options.php">
<?php wp_nonce_field('update-options'); ?>
<h2>Enter Text: </h2>
<textarea name="my_first_data" id="my_first_data" cols="200" rows="20"></textarea>
<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="my_first_data" /><br />
<input style="position: fixed; left: 40%;" id="mailinglistsubmit" type="submit" value="Save Changes" /><img src="<?php admin_url(); ?>/wp-admin/images/wpspin_light.gif" alt="" class="ajaxsave" style="display: none;" />
</form>
</p>
</div>
<?php
}
?>
<?php add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
?>
<?php function join_mailinglist_callback() {
$email = $_POST['email'];
if(!empty($email)) {
$yourEmail = 'c#bavotasan.com';
$subject = 'Add me to your mailing list';
$success = mail($yourEmail, $subject, $email);
if(!empty($success)) {
echo 'Your email is subscribed to our mailing list.';
} else {
echo 'There was a problem. Please try again.';
}
}
die();
} ?>
<style>
.content { padding-left:150px;}
.output p {width:700px; height:auto;}
</style>
I see several things wrong with this plugin of yours.
Firstly, why is your JavaScript code appended to the top of the plugin? The right way to include JS in WordPress is to have it in a separate .js file and loaded by enqueing it using wp_enqueue_script(). Same for your styles at the bottom.
An example is as follows:
function my_scripts_method() {
wp_enqueue_script(
'your-script-name',
plugins_url( 'js/your-script.js' , __FILE__ ),
array('jquery')
);
}
add_action('wp_enqueue_scripts', 'my_scripts_method');
Secondly, your PHP plugin file MUST NOT be outputting any content and that means you shouldn't see any ?> tags after the headers as that would output a few linebreaks.
Next, in order to get the admin-ajax-url in your static JS file, you should use this function:
wp_localize_script( 'ajax_get_permalink', 'ajax_get_permalink', array(
ajax_url => admin_url( 'admin-ajax.php' )
));
In your JS file, you should wrap your main code in a function that is called when the form submits.
function mailingListSubmit() {
var data = {
action: 'join_mailinglist',
email: jQuery('#mailingListEmail')
};
jQuery("#mailinglistsubmit").hide();
jQuery(".ajaxsave").show();
jQuery.post(ajax_get_permalink.ajax_url, data,
function(response){
jQuery(".ajaxsave").hide();
jQuery("#mailinglistsubmit").show();
});
}
And finally, your action hooks are wrong too. You copied it from the codex (or who knows where) but didn't even bother to read the docs.
add_action('wp_ajax_my_action', 'my_action_callback');
You need to change my_action_callback to reflect your function name join_mailinglist_callback and wp_ajax_my_action to wp_ajax_join_mailinglist -- the action you defined in your JS file.
The above codes aren't tested for syntax errors but should point you in the right direction. You shouldn't expect your plugin to magically work even if you copy and paste these code in.
Read more about AJAX in WordPress plugins here: http://codex.wordpress.org/AJAX_in_Plugins

How do you write forms?

in your framework are there any automation to build forms?
For example let's say you have this array of fields:
$fields = array('name'=>array('type'=>'input',otherparams)
'desc'=>array('type'=>'textarea',otherparams)
);
based on fields you should make HTML like this:
<form>
Name: <input name="name" type="text">
Description: <textarea name="desc"></textarea>
//>Submit
</form>
Do you build your html by-hand or is there some sort of automation?
Thanks
I work with the Yii framework. The php generates the html automatically. You write some html by hand but it's for the views. The views also have dynamic php variables that change. The actually full html document is put together by calling a controller with the web address, that controller deciding what models if any it needs to apply to the form and what view to put the model in. Then it generates the html.
SiteController.php
<?php
class SiteController extends Controller
{
/**
* Declares class-based actions.
*/
public function actions()
{
return array(
// captcha action renders the CAPTCHA image displayed on the contact page
'captcha'=>array(
'class'=>'CCaptchaAction',
'backColor'=>0xFFFFFF,
),
// page action renders "static" pages stored under 'protected/views/site/pages'
// They can be accessed via: index.php?r=site/page&view=FileName
'page'=>array(
'class'=>'CViewAction',
),
);
}
/**
* This is the default 'index' action that is invoked
* when an action is not explicitly requested by users.
*/
public function actionIndex()
{
// renders the view file 'protected/views/site/index.php'
// using the default layout 'protected/views/layouts/main.php'
$this->render('index');
}
/**
* This is the action to handle external exceptions.
*/
public function actionError()
{
if($error=Yii::app()->errorHandler->error)
{
if(Yii::app()->request->isAjaxRequest)
echo $error['message'];
else
$this->render('error', $error);
}
}
/**
* Displays the contact page
*/
public function actionContact()
{
$model=new ContactForm;
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$headers="From: {$model->email}\r\nReply-To: {$model->email}";
mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);
Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
$this->refresh();
}
}
$this->render('contact',array('model'=>$model));
}
/**
* Displays the login page
*/
public function actionLogin()
{
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}
/**
* Logs out the current user and redirect to homepage.
*/
public function actionLogout()
{
Yii::app()->user->logout();
$this->redirect(Yii::app()->homeUrl);
}
}
ContactForm.php = This is the model.
<?php
/**
* ContactForm class.
* ContactForm is the data structure for keeping
* contact form data. It is used by the 'contact' action of 'SiteController'.
*/
class ContactForm extends CFormModel
{
public $name;
public $email;
public $subject;
public $body;
public $verifyCode;
/**
* Declares the validation rules.
*/
public function rules()
{
return array(
// name, email, subject and body are required
array('name, email, subject, body', 'required'),
// email has to be a valid email address
array('email', 'email'),
// verifyCode needs to be entered correctly
array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
);
}
/**
* Declares customized attribute labels.
* If not declared here, an attribute would have a label that is
* the same as its name with the first letter in upper case.
*/
public function attributeLabels()
{
return array(
'verifyCode'=>'Verification Code',
);
}
}
This is the view:
contact.php
<?php
$this->pageTitle=Yii::app()->name . ' - Contact Us';
$this->breadcrumbs=array(
'Contact',
);
?>
<h1>Contact Us</h1>
<?php if(Yii::app()->user->hasFlash('contact')): ?>
<div class="flash-success">
<?php echo Yii::app()->user->getFlash('contact'); ?>
</div>
<?php else: ?>
<p>
If you have business inquiries or other questions, please fill out the following form to contact us. Thank you.
</p>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm'); ?>
<p class="note">Fields with <span class="required">*</span> are required.</p>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'email'); ?>
<?php echo $form->textField($model,'email'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'subject'); ?>
<?php echo $form->textField($model,'subject',array('size'=>60,'maxlength'=>128)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'body'); ?>
<?php echo $form->textArea($model,'body',array('rows'=>6, 'cols'=>50)); ?>
</div>
<?php if(CCaptcha::checkRequirements()): ?>
<div class="row">
<?php echo $form->labelEx($model,'verifyCode'); ?>
<div>
<?php $this->widget('CCaptcha'); ?>
<?php echo $form->textField($model,'verifyCode'); ?>
</div>
<div class="hint">Please enter the letters as they are shown in the image above.
<br/>Letters are not case-sensitive.</div>
</div>
<?php endif; ?>
<div class="row buttons">
<?php echo CHtml::submitButton('Submit'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<?php endif; ?>
Going to the page: http://yoursite/index.php/contact/ activates the actionContact method in the SiteController. That grabs the posted contact information, puts it into a model, and then renders a view.
CodeIgniter allows you to build forms using the Form Helper, although I prefer to write the HTML myself.
try this(not tested)
<?php
$fields = array('name'=>array('type'=>'input',name='fname')
'desciprtion'=>array('type'=>'textarea',name='desc')
);
?>
<form name="myform" action="" method="post">
<?php
foreach($fields as $key=>$value)
{
echo "<label>$key</label>";
echo " <$key['type'] name=\"$key['name']\" id=\"$key['id']>\">
}
?>

Categories