I am newbie to the wordpress. I have created a custom installable plugin. Now i want that When this plugin is installed at that time some tables should be migrated to the database required by this plugin.
Any help will be helpful. Thank you.
You can register an activation hook. This will fire when your plugin is activated and do what you want it to do. In combination with dbDelta you can execute the creation of a table (or the alteration if a new version requires different layout of your table).
A working example is provied:
<?php
global $jal_db_version;
$jal_db_version = '1.0';
function jal_install() {
global $wpdb;
global $jal_db_version;
$table_name = $wpdb->prefix . 'liveshoutbox';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
name tinytext NOT NULL,
text text NOT NULL,
url varchar(55) DEFAULT '' NOT NULL,
UNIQUE KEY id (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
add_option( 'jal_db_version', $jal_db_version );
}
function jal_install_data() {
global $wpdb;
$welcome_name = 'Mr. WordPress';
$welcome_text = 'Congratulations, you just completed the installation!';
$table_name = $wpdb->prefix . 'liveshoutbox';
$wpdb->insert(
$table_name,
array(
'time' => current_time( 'mysql' ),
'name' => $welcome_name,
'text' => $welcome_text,
)
);
}
register_activation_hook( __FILE__, 'jal_install' );
register_activation_hook( __FILE__, 'jal_install_data' );
?>
Related
I'm trying to update a row in a custom table (or update if the 'user_id' exists) when creating or updating a user profile. The source data is the 'location' field - an ACF field.
Currently the custom table doesn't get updated on profile create or save. Here's what I have so far:
function copy_location_to_user_locations( $user_id ) {
if ( !current_user_can( 'edit_user', $user_id ) ) {
return false;
}
$location = get_field('location', 'user_'.$user_id); // Needs to match the ACF field name
$latitude = $location['lat'];
$longitude = $location['lng'];
global $wpdb;
$table_name = $wpdb->prefix . 'user_locations';
$data = array(
'user_id' => $user_id,
'latitude' => $latitude,
'longitude' => $longitude
);
$wpdb->replace( $table_name, $data );
}
add_action( 'profile_update', 'copy_location_to_user_locations', 10, 1 );
add_action( 'user_register', 'copy_location_to_user_locations', 10, 1 );
What have I missed?
For reference, my function for creating the custom table is:
function create_user_locations_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'user_locations';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id bigint(20) NOT NULL AUTO_INCREMENT,
user_id bigint(20) UNSIGNED NOT NULL,
latitude float(10,6) NOT NULL,
longitude float(10,6) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (user_id) REFERENCES {$wpdb->users}(ID)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
}
register_activation_hook( __FILE__, 'create_user_locations_table' );
I know the title makes it look like a question that has been answered already but I checked the similar questions and I'm still not answered.
I have a custom table created with the following code:
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
meta_id int(9) NOT NULL,
copied tinyint(1) NULL,
local_url varchar(55) DEFAULT '' NOT NULL,
s3_url varchar(55) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
I'm trying to insert rows into it using the following code but nothing is happening:
$table_name = $wpdb->prefix . 's3images';
$wpdb->insert(
$table_name,
array(
'local_url' => $local_url,
's3_url' => $s3_url,
'meta_id' => $meta_id,
'copied' => 0,
)
);
Where am I messing up?
Use following query to insert new row in your custom database table
$sql = "INSERT INTO ".$table_name." set local_url='".$local_url."',s3_url='".$s3_url."',meta_id='".$meta_id."',copied='".$copied." ";
$results = $wpdb->query($sql);
So I am busy creating a plugin that creates a custom table to read in some data.
The plugin works 100% on localhost but does not create the table in the db on the real host.
I have debug enables and there does not seem to be a problem.
I have tried query but no luck
On localhost the wordpress installation is in the root file but on the server the wordpress installation is in a folder called v in the root file. (might make a difference?)
The basic code is
<pre><code>
function elite_fuel_installl() {
global $wpdb;
$table_name = $wpdb->prefix . "test";
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
timeDataCollected datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
ULP93Inland text NOT NULL,
ULP95Inland text NOT NULL,
ULP93Coastal text NOT NULL,
ULP95Coastal text NOT NULL,
Diesel005 text NOT NULL,
Diesel0005 text NOT NULL,
UNIQUE KEY id (id)
);";
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
dbDelta( $sql );
$rows_affected = $wpdb->replace( $table_name, array
( 'id' => $idd, 'timeDataCollected' => current_time('mysql'),
'ULP93Inland' => $ULP93Inland, 'ULP95Inland' => $ULP95Inland,
'ULP93Coastal' => $ULP93Coastal,'ULP95Coastal' => $ULP95Coastal,
'Diesel005' => $Diesel005,'Diesel0005' => $Diesel0005) );
}
register_activation_hook( __FILE__, 'elite_fuel_installl' );
</code></pre>
Thanks
I am building a CakePHP 2.3 application, and can't for the life of me figure out why saveAll keeps failing.
I have the following models:
Artist hasMany ArtistPreview
ArtistPreview belongsTo Artist
I have no problem saving my Artist model with the save() function, however as soon as I try to use the saveAll method, Cake seems to fail validation - which is crazy because I have even totally removed all my validation rules from my models.
Here's my view, nothing crazy:
<?php
echo $this->Form->create('Artist', array('inputDefaults' => array('class' => 'input-block-level')));
echo $this->Form->input('Artist.name', array('label' => __('Name')));
echo $this->Form->input('Artist.artist_section_id', array('label' => __('Section'), 'empty' => true));
?>
<label>Tags</label>
<div class="checkboxes">
<?php echo $this->Form->input('Tag', array('label' => false, 'multiple' => 'checkbox', 'class' => false));; ?>
</div>
<?php
echo $this->Form->input('Artist.website', array('label' => __('Website')));
echo $this->Form->input('ArtistPreview.0.url', array('label' => __('Artist Preview')));
echo $this->Form->input('Artist.description', array('label' => __('Description')));
?>
<?php
echo $this->Form->submit(__('Add'), array('class' => 'btn btn-primary btn-large', 'div' => false)) . ' ';
echo $this->Form->button(__('Cancel'), array('type' => 'button', 'class' => 'btn btn-large', 'div' => false, 'onclick' => 'closeDialog()'));
echo $this->Form->end();
?>
And here's my add controller method:
public function add() {
$this->layout = 'form';
if (!$this->request->is('ajax')) {
throw new ForbiddenException();
}
if ($this->request->is('post')) {
$this->setData($this->request->data['Artist'], array(
'user_id' => AuthComponent::user('id'),
'date' => $this->Date->gmt()
));
if ($this->Artist->saveAll($this->request->data)) {
$this->redirectAjax('/artists/view/' . $this->Artist->id);
}
}
$this->set(array(
'title_for_layout' => 'Add Artist',
'artistSections' => $this->Artist->ArtistSection->find('list', array('order' => 'name')),
'tags' => $this->Artist->Tag->find('list', array('order' => 'name'))
));
}
As I mentioned above, the saveAll method fails everytime. I have inspected what is getting output and Cake is outputting a bunch of blank <div>s with the error-message class, but there is no message. Every field on the form gets one of these divs.
Now, when I change my code to use the save function instead of saveAll, everything gets saved properly except the ArtistPreview data, which is to be expected. Even my HABTM Tags are being saved properly, and nothing fails validation.
I have been using Cake since the 1.3 days so I'm quite familiar with it, and have even done exactly what I'm asking in previous projects. I'm leaning towards this being a bug, unless I'm missing something here. Any ideas?
EDIT
I have also tried the saveAssociated method, along with setting the deep key to true when trying to save. This will let me save the artist, but it will not save the related data (ArtistPreview).
EDIT 2
As requested, here are the two tables:
-- -----------------------------------------------------
-- Table `artists`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `artists` ;
CREATE TABLE IF NOT EXISTS `artists` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`user_id` INT UNSIGNED NULL ,
`artist_section_id` INT UNSIGNED NULL ,
`artist_status_id` INT UNSIGNED NULL ,
`name` VARCHAR(200) NULL ,
`website` VARCHAR(500) NULL ,
`description` TEXT NULL ,
`date` DATETIME NULL ,
`comment_count` INT UNSIGNED NOT NULL DEFAULT 0 ,
PRIMARY KEY (`id`) ,
INDEX `FK_artists_users_idx` (`user_id` ASC) ,
INDEX `FK_artists__artist_sections_idx` (`artist_section_id` ASC) ,
INDEX `FK_artists__artist_statuses_idx` (`artist_status_id` ASC) ,
CONSTRAINT `FK_artists__users`
FOREIGN KEY (`user_id` )
REFERENCES `users` (`id` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `FK_artists__artist_sections`
FOREIGN KEY (`artist_section_id` )
REFERENCES `artist_sections` (`id` )
ON DELETE SET NULL
ON UPDATE CASCADE,
CONSTRAINT `FK_artists__artist_statuses`
FOREIGN KEY (`artist_status_id` )
REFERENCES `artist_statuses` (`id` )
ON DELETE SET NULL
ON UPDATE CASCADE)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `artist_previews`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `artist_previews` ;
CREATE TABLE IF NOT EXISTS `artist_previews` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`artist_id` INT UNSIGNED NULL ,
`url` VARCHAR(500) NULL ,
`date` DATETIME NULL ,
PRIMARY KEY (`id`) ,
INDEX `FK_artist_previews__artists_idx` (`artist_id` ASC) ,
CONSTRAINT `FK_artist_previews__artists`
FOREIGN KEY (`artist_id` )
REFERENCES `artists` (`id` )
ON DELETE CASCADE
ON UPDATE CASCADE)
ENGINE = InnoDB;
Here is my setData function, which just merges two arrays. Instead of using hidden fields, I set fields in the controller which aren't populated by user input:
public function setData(&$original, $new) {
$original = array_merge($original, $new);
}
So I finally figured this out, and wow was it a rookie mistake. I think I must've been half asleep yesterday when I was coding. The problem was in my model:
class Artist extends AppModel {
public $belongsTo = array(
'User',
'ArtistSection',
'ArtistStatus'
);
public $hasMany = array(
'ArtistPicture',
'Artist' // <--- problem was here, had 'Artist' instead of 'ArtistPreview'
);
public $hasAndBelongsToMany = array(
'Tag'
);
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->validate = array(
'name' => array(
'rule' => 'notEmpty',
'message' => __('Artist name cannot be blank.')
),
'website' => array(
'rule' => 'url',
'message' => __('Must be a valid URL.'),
'allowEmpty' => true
),
'artist_section_id' => array(
'rule' => 'notEmpty',
'message' => __('Section is required.')
)
);
}
}
Thank you to those of you who took the time to look at this question, even though I posted the wrong information.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have been trying to integrate Google login to one of my sites that is being developed using CakePHP framework. So far I have been unsuccessful in doing so. Does anybody have any idea how to do that ?
Which version of CakePHP are you using ?
However, you should take a look to that thread : CakePHP OAuth with Google
There is also good ressources on CakePHP / providers authentications :
https://github.com/corefactor/CakePHP-Oauth-Plugin
http://code.42dh.com/oauth/
http://code.42dh.com/openid/
http://cutfromthenorth.com/integrating-facebook-connect-with-cakephps-auth-component/
Hiii ...Pls Follow Step by step .
Step 1: First of all , U should download Google files From github or any in ../app/Vendor directory ....
Make sure that Google files includes following files ..
Auth folder, cache folder, contrib folder, external folder,io folder,service folder & autoload.php file,config.php file, Google_Client.php file .
Step 2 : Create Users table .
CREATE TABLE IF NOT EXISTS `users` (<br>
`id` int(11) NOT NULL AUTO_INCREMENT,<br>
`first_name` varchar(60) DEFAULT NULL,<br>
`last_name` varchar(60) DEFAULT NULL,<br>
`email` varchar(80) DEFAULT NULL,<br>
`password` varchar(64) DEFAULT NULL,<br>
`social_id` varchar(45) DEFAULT NULL,<br>
`picture` varchar(100) DEFAULT NULL,<br>
`gender` char(1) DEFAULT NULL,<br>
`created` datetime DEFAULT NULL,<br>
`updated` datetime DEFAULT NULL,<br>
`uuid` varchar(70) DEFAULT NULL,<br>
`status` int(11) DEFAULT NULL,<br>
PRIMARY KEY (`id`),<br>
KEY `email_idx` (`email`)<br>
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
NOTE : All Fields are not mandatory . Ur wish .
Step 3: Then U should Create Client ID & Client Secret key for your app/website at https://developers.google.com/
Refer : https://theonetechnologies.com/blog/post/how-to-get-google-app-client-id-and-client-secret for steps .
Step 4 : Now you should have your own Client ID & Client Secret key.
Step 5: Add these five lines in your ../app/config/bootstrap.php file
define('GOOGLE_APP_NAME', 'Smart Quiz');<br>
define('GOOGLE_OAUTH_CLIENT_ID', 'YOUR CLIENT_ID');<br>
define('GOOGLE_OAUTH_CLIENT_SECRET', 'YOUR CLIENT_SECRET');<br>
define('GOOGLE_OAUTH_REDIRECT_URI', 'http://localhost/cakelogin/google_login');<br>
define("GOOGLE_SITE_NAME", 'https://your site/');
& fill your Client Id , Secret key , Redirect URI & site url .
Ex format:
Client id : xxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com<br>
Secret key : xxxxxxxxxxxxxxxxxxxxxxxx<br>
Redirect URI : https://your site/google/google_login
NOTE : Redirect uri (i.e) your site should be "https" . It won't allow http site .
Step 6: Create google_login.php file in the app/Config directory and including following files. Here is my code.
<?php<
require_once '../Vendor/Google/src/config.php';
require_once '../Vendor/Google/src/Google_Client.php';
require_once '../Vendor/Google/src/contrib/Google_PlusService.php';
require_once '../Vendor/Google/src/contrib/Google_Oauth2Service.php';
NOTE : Make sure the Vendor directory path & file locations are in correct .
Step 7 : In view file , add this link in
href="https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=YOUR REDIRECT URI&client_id=YOUR CLIENT ID.apps.googleusercontent.com&scope=email+profile&access_type=online&approval_prompt=auto"
Step 8: Create GoogleController . Copy below Code.
App::import('Vendor', 'google', array('file' => 'google/config.php'));<br>
App::import('Vendor', 'google', array('file' => 'google/Google_Client.php'));<br>
App::import('Vendor', 'google', array('file' => 'google/contrib/Google_PlusService.php'));<br>
App::import('Vendor', 'google', array('file' => 'google/contrib/Google_Oauth2Service.php'));<br>
class GoogleController extends AppController {<br>
public $components = array('Paginator', 'Session');<br>
public $uses = array('User');<br>
public $layout = '';<br>
public function google_login() {
$this->autoRender = false;
require_once '../Config/google_login.php';
$client = new Google_Client();
$client->setScopes(array('https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/plus.me'));
$client->setApprovalPrompt('auto');
$plus = new Google_PlusService($client);
$oauth2 = new Google_Oauth2Service($client);
if (isset($_GET['code'])) {
$client->authenticate(); // Authenticate
$_SESSION['access_token'] = $client->getAccessToken(); // get the access token here<br>
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
$user = $oauth2->userinfo->get();
try {
if (!empty($user)) {
$check = $this->User->find('first', array('conditions' => array('email' => $user['email'], 'status !=' => 'Trash')));
if (empty($check)) {
$data = array();
$data['email'] = $user['email'];
$data['name'] = $user['given_name'];
$data['user_name'] = $this->random_username($user['given_name']);
$this->User->save($data);
$id = $this->User->getLastInsertID();
$currentuser = $this->User->find('first', array('conditions' => array('user_id' => $id, 'status !=' => 'Trash')));
$this->Session->write('User', $currentuser['User']);
$this->Session->write('Userlogin', TRUE);
$this->Session->setFlash('Logged in Successfully !', '', array(''), 'front_success');
return $this->redirect(array('action' => 'profile', 'controller' => 'users'));
} else {
$this->Session->write('User', $check['User']);
$this->Session->write('Userlogin', TRUE);
$this->Session->setFlash('Logged in Successfully !', '', array(''), 'front_success');
return $this->redirect(array('action' => 'profile', 'controller' => 'users'));
}
}
} catch (Exception $e) {
$this->Session->setFlash(GOOGLE_LOGIN_FAILURE, 'default', array('class' => 'message error'), 'error');
$this->redirect(BASE_PATH . 'login');
}
}
}
}
Step 9 : In app/Vendor/google/config.php file , u can see the application name , oauth2_client_id , oauth2_client_secret, oauth2_redirect_uri . So you have to give ur details on that . Example :
'application_name' => 'YOUR APPLICATION NAME',<br>
'oauth2_client_id' => 'YOUR CLIENT ID',<br>
'oauth2_client_secret' => 'YOUR SECRET KEY',<br>
'oauth2_redirect_uri' => 'https://your site/google/google_login', <br>
Thats it ! :)
Problems that i faced is , I wrongly mention the REDIRECT URI in facebook developers & in Config.php file . So You should provide same Redirect path in your bootstrap.php file , config.php file , href="" link & in developers site .
Hope it will help ... Thank You .