local wordpress using remote database, ubuntu, apache2 - php

im trying to connect my local wordpress install to a db on a domain i own using the code provided here:
https://coderwall.com/p/ck8v4a/remote-database-with-local-wordpress-instance
define('WP_CACHE', true); $currenthost = $_SERVER['HTTP_HOST'];
$mypos = strpos($currenthost, 'localhost/wpdir');
if ($mypos === false) {
define('WP_HOME','http://example.org/wpDir/');
define('WP_SITEURL','http://example.org/wpDir/');
} else {
define('WP_HOME','http://localhost');
define('WP_SITEURL','http://localhost/wpDir/');
}
with the above config i can open the site locally, it loads the navigation and recent post names correctly, so the db-connection seems to work.
i cannot use links and pages are not found though.
if i add my /wpDir/ to the define('WP_HOME'... and/or strpos($currenthost,... it gets redirected to http://localhost/wpDir/home/ (as it should) but i get an URL not found error.
my localhost dir is standard /var/www/html this is where my local wordpress installations are.
any ideas how to fix this?
update: i am back to working on this and it would really help a lot if i could manage to use the remote database for my local testing
i think it may be some kind of url rewriting problem but all my efforts to find a solution did not work...

not sure why it was so hard to find but i managed to do it (another way) basically by following the wp-codex here:
https://codex.wordpress.org/Running_a_Development_Copy_of_WordPress
using the drop-in method:
the code in my db.php file looks like this:
<?php
// paste this in a (new) file, wp-content/db.php
add_filter ( 'pre_option_home', 'test_localhosts' );
add_filter ( 'pre_option_siteurl', 'test_localhosts' );
function test_localhosts( ) {
if (strcasecmp($_SERVER['REQUEST_URI'], '/localCopyOfSite') == 0
|| strcasecmp(substr($_SERVER['REQUEST_URI'], 0, 17), '/localCopyOfSite/') == 0) {
return "http://localhost/localCopyOfSite/";
}
else return false; // act as normal; will pull main site info from db
}

Related

Custom Cache per Country - Wordpress php [Disable Cache from function]

On our website at www.EllasBubbles.com, we are using a functions.php script to execute an alternative stylesheet to users who are outside of U.S/Canada. This script is as follows:
// [International] - Dark Mode
add_action( 'wp_head' , 'custom_inline_css', 200 );
function custom_inline_css() {
// Get an instance of the WC_Geolocation object class
$geolocation_instance = new WC_Geolocation();
// Get user IP
$user_ip_address = $geolocation_instance->get_ip_address();
// Get geolocated user IP country code.
$user_geolocation = $geolocation_instance->geolocate_ip( $user_ip_address );
// For all countries except 'US'
if($user_geolocation['country'] !== 'US' && $user_geolocation['country'] !== 'CA'){
?>
<style>
<?php include 'international.php'; ?>
</style>
<?php
}
}
We use cloud flare to manage our Cache. I have properly setup bypass rules for these two files:
ellasbubbles.com/wp-content/themes/flatsome/international.php
ellasbubbles.com/wp-content/themes/flatsome/assets/css/flatsome.css
When loading the site from an international VPN, the "Dark Mode" (Outside U.S/Canada) version is displayed. However, when disabling the VPN; we are stuck on Dark Mode. Which is a bypassed file with Cloudflare Cache - and simply makes no sense to me.
This leads me to believe that the instance of the WC_Geolocation class is being cached somewhere on the Wordpress website. I have searched everywhere for a solution, and can not determine the best way to perform this custom CSS per country. Can we disable caching from function custom_inline_css ? Should I change international.php to css? Is there a better way to go about this?
Update 1: When I disabled caching from the entire website in cloud flare, this works fine!
Update 2: When I disable caching from everything inside ellasbubbles.com/wp-content/*; this still does not work properly..what file am I missing?
Update 3: I disabled all folders one by one to no avail
Please help me help everyone

Moodle plugin : check if admin + add link to plugin in administration

I'm new to moodle plugin development and am trying to create a plugin that displays a page to the admin where I can add my on php code.
In brief, what I want the plugin to do I have already achieved in a standard php file that I upload to the moodle root. From here you can call the file e.g. yourdomain.co.uk/moodlelocation/myfile.php and it will run as expected.
The problem with this is it isn't secure since anyone can load the myfile.php and in turn run the scripts on the page. It also means any one else using this script (it will be given away for free when complete) would need to FTP into their hosting and upload two php files to their moodle install.
Due to this, I thought a plugin (a very very basic plugin) may be the best solution. They could then load the page in the admin via the "site administration". e.g. site administration > Development > MyPlugin. I am assuming I could then also restrict the plugin's main page to admins only (??).
So to recap, I can create a php page that has my script all rocking and rolling BUT I need to make this into a plugin.
I did some reading and I think a "local" plugin was the easiest way to go (??).
I have managed to get the local plugin up and running using the below in local/webguides/inex.php :
<?php
// Standard config file and local library.
require_once(__DIR__ . '/../../config.php');
// Setting up the page.
$PAGE->set_context(context_system::instance());
$PAGE->set_pagelayout('standard');
$PAGE->set_title("webguides");
$PAGE->set_heading("webguides");
$PAGE->set_url(new moodle_url('/local/webguides/index.php'));
// Ouput the page header.
echo $OUTPUT->header();
echo 'MY php CODE here etc';
?>
This works fine but with two problems:
Anyone can access it via http://domain/local/webguides/index.php
There is no link to it in the site administration (so the user would need to type the URL in).
Can anyone shed any light how I would achieve the two steps above?
Thanks in advance
p.s. ideally I'd like to keep the plugin to as few files as possible so if the required code could be added to the local/webguides/index.php file it would be preferred.
You need to create a capability, then require that capability before displaying the page.
First, have a look at local/readme.txt - this gives an overview of the files needed for a local plugin.
Or read the documentation at https://docs.moodle.org/dev/Local_plugins
Also have a look at existing local plugins so you can see how they are created - https://moodle.org/plugins/?q=type:local
At a bare minimum, you need
local/webguides/db/access.php - this will have the capability
local/webguides/lang/en/local_webguides.php
local/webguides/version.php
Plus your index file
local/webguides/index.php
In the db/access.php file have something like
defined('MOODLE_INTERNAL') || die();
$capabilities = array(
'local/webguides:view' => array(
'captype' => 'read',
'contextlevel' => CONTEXT_SYSTEM,
'archetypes' => array(
),
),
);
You might also need 'riskbitmask' => RISK_XXX depending on if there are any risks in you code. Such as RISK_CONFIG, RISK_PERSONAL, etc.
In lang/en/local_webguides.php have something like
defined('MOODLE_INTERNAL') || die();
$string['pluginname'] = 'Webguides';
$string['webguides:view'] = 'Able to view webguids';
In version.php have something like
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2020051901; // The current plugin version (Date: YYYYMMDDXX)
$plugin->requires = 2015051109; // Requires this Moodle version.
$plugin->component = 'local_webguides'; // Full name of the plugin (used for diagnostics).
Replace 2015051109 with the version of Moodle you are using - this will be in version.php in the root folder.
Then in your index.php file use this near the top.
require_capability('local/webguides:view', context_system::instance());
So only users with that capability will have access to the page.
EDIT:
You can add a link via settings.php using something like
defined('MOODLE_INTERNAL') || die;
if ($hassiteconfig) {
$page = new admin_externalpage(
'local_webguides',
get_string('pluginname', 'local_webguides'),
new moodle_url('/local/webguides/index.php'),
'local/webguides:view'
);
$ADMIN->add('localplugins', $page);
}
Then in your index page ad this
require_once($CFG->libdir.'/adminlib.php');
and remove require_login() and require_capability() and replace with
admin_externalpage_setup('local_webguides');

In wordpress I am manipulation 404 response. I want to give the response before 404 error is given to google

May be the question in title is not explaining what exactly I want. So I will explain one logic and then ask what problem I am getting from that.
We are using wordpress.
We have 2 categories Option1(Having 64 different values) and Option2(Having 8 different values). We wanted url like ourdomain/Option1/Option2 depending on users location. And data on that url will be specific according to that Option1 and Option2. We dont wanted all this 64*8 actual wordpress pages to be created.
So after searching much on net we had one solution that I implemented one plugin for routing.
IN that code snippet was as follow.
function site_router() {
global $route,$wp_query,$window_title;
error_reporting(E_ALL);
if ( $wp_query->is_404 )
{
$wp_query->is_404 = false;
$cUrl="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$targetUrl="";
switch($cUrl)
{
/* According to condition I had written diffent cases like below.
*/
default :
{
include(get_template_directory() . "/home.php" );
$template =locate_template('pagepath/home.php');
$window_title = 'dynamically it will come';
if ($template) {
load_template($template);
die;
}
}
}
}
}
add_action( 'wp', 'site_router');
So by this my purpose was fulfilled successfully.
But now problem is that google is saying they are getting back a 404 error. I think obviosly it will give as after it gives the error we are doing all template loading and all stuff.
So Can any body guide me how can I do this before that 404 response is given to google.
I posted the question on wordpress stackexchange and got the answer over there. the link is as below.
https://wordpress.stackexchange.com/questions/70345/in-wordpress-i-am-manipulation-404-response-i-want-to-give-the-response-before

Wordpress Future Page Issue (Not Showing)

I've been asked to fix a problem on a wordpress site. The problem is caused by the fact posts should of been used instead of pages. However the site is up and running and quickest option would be to fix the problem using a hack of sorts.
The site has an events section, each event is a page (this is the issue, should really be a post). In order to have upcoming and past events the post date is used, therefore upcoming events has a post status of 'future'.
There's are list page of events which shows them fine by using the correct query_post(). Although the problem arises when you click through to actual event (which is a future page). If your logged in as an Admin then the page shows but if your not logged in you get a 404 page.
Now if they where posts then the "The Future is Now!" plugin would solve this problem. I have a feeling the only way round the problem is to rewrite part of core Wordpress files.
Any advice would be great, I have a lot of experience with Wordpress so even if you can point me in the right direction.
Cheers,
Jason
[Update]
Thanks maiorano84 for your detailed response. In the long run I intend to move them to posts but in the meantime they've requested we fix it asap without changing any urls (today they sent out a mass email with a list of events without checking any links)
Your solution of including post_status future doesn't work in this case as wordpress doesn't get to the stage of loading the template. Something in wordpress core stops it from getting that far. Ideally if they was a hook I could use to override this behavior in the meantime that would be excellent but if it comes to it I will temporarily edit the core files.
[Update 2]
I now know the two functions that need editing or use a hook that relates to them.
First of we is_404() which needs changed to not add future pages as 404
Second we have is_page() need to return true if a page is future
[Update 3]
I've found how to do this in the core. If you go to wp-includes/query.php line 2682. Copy this in instead of the old function it works correct. If you have a better way please let me know. Thanks.
/** Future Pages **/
// Check post status to determine if post should be displayed.
if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
$status = get_post_status($this->posts[0]);
$post_status_obj = get_post_status_object($status);;
if ( !$post_status_obj->public ) {
if ( $post_status_obj->protected ) {
$this->is_preview = true;
print_r($status);
if ( 'draft' != $status ) {
$this->posts[0]->post_date = current_time('mysql');
} else {
$this->posts = array();
}
} elseif ( $post_status_obj->private ) {
if ( ! current_user_can($read_cap, $this->posts[0]->ID) )
$this->posts = array();
} else {
$this->posts = array();
}
}
/** END **/
You can actually add a post_status parameter of 'future' to your page queries. You REALLY shouldn't be modifying your core files in order to do what you want. So on your page.php and archive.php templates (or other relevant templates that's controlling your Event display), you can do something like this:
<?php
$params = array('posts_per_page'=>-1, 'post_status'=>'publish,future');
$query = new WP_Query($params);
if($query->have_posts()) : while($query->have_posts()) : $query->the_post();
?>
<!-- YOUR PAGE HTML HERE -->
<?php
endwhile;endif;
wp_reset_postdata();
?>
This is an oversimplification, but using the correct queries in the corresponding files will allow you to display your pages however you like.
More information here: http://codex.wordpress.org/Class_Reference/WP_Query
Another thing worth considering, and I realize that this wasn't a part of your question, but may very well solve your issue:
Why not create a subdomain on your client's server where you can work on fixing everything without interrupting the user experience? You can easily either import the existing database into your development environment, and make all the changes you need without affecting the live version.
Food for thought. My advice would be to nip this in the bud, and convert the pages over to posts as soon as possible, otherwise the website will turn into a giant mess very quickly, but that's your call.
Hope this helps.
UPDATE:
I would still advise against altering the core files, but if it's a last resort until everything gets fixed, then have at it. Here's is a "WP Friendly" solution I think might help:
add_action('wp','future_redirect', 0);
function future_redirect($WP_Object)
{
$page = is_page() ? get_page(get_the_ID()) : false;
if($page && $page->post_status == 'future')
{
wp_redirect(/*YOUR REDIRECT URL*/);
exit();
}
return $WP_Object;
}

Need to activate a plugin for a wordpress site through the php files

I was going to update the ecommerce plugin (Shopp) on my wordpress site and it asked me to deactivate it. once I did that I lost the entire site.
I am trying to activate the plugin through the php files, but not sure what I am doing and would like some help.
Does anyone know how I can activate the Shopp plugin (or any plugin for that matter) on my site through the php files?
This is the code I'm using to get the string:
$unserialized = unserialize('a:14:{i:0;s:19:"akismet/akismet.php";i:1;s:37:"breadcrumbs-plus/breadcrumbs-plus.php";i:2;s:35:"googleanalytics/googleanalytics.php";i:3;s:45:"grunion-contact-form/grunion-contact-form.php";i:4;s:43:"image-caption-links/image-caption-links.php";i:5;s:29:"image-widget/image-widget.php";i:6;s:13:"rate/rate.php";i:7;s:33:"restore-jquery/restore-jquery.php";i:8;s:41:"shopp-cache-helper/shopp-cache-helper.php";i:9;s:47:"shopp-default-breadcrumb-extender-sdbe/sdbe.php";i:10;s:33:"shopp-improved/shopp-improved.php";i:11;s:19:"shuffle/shuffle.php";i:12;s:19:"vslider/vslider.php";i:13;s:41:"wordpress-importer/wordpress-importer.php";}');
array_push($unserialized, 'shopp/shopp.php');
$serialized = serialize($unserialize);
echo $serialized;
The active plugins are not stored in a PHP file. It's stored in the database. Open the wp_options table in the database. Look for a row in which the value of the option_name field is active_plugins. In this row, look for the value of option_value. You'll see a serialized string containing the information of the active plugins.
Now, it might be a little bit confusing to edit the string straight away especially if you're not familiar how serialized strings are formatted. So, I suggest you copy the string and use PHP unserialize() function on it, which will then return an array. After that, use array_push() to add another element in which the value is the path to the plugins file (e.g. "akismet/akismet.php", in your case it might be "shopp/shopp.php"). Once you've add another element, use serialize() and copy the returned string and replace the old serialized string in the database.
$unserialized = unserialize('...');
array_push($unserialized, 'shopp/shopp.php');
$serialized = serialize($unserialized);
echo $serialized; // Copy this output back into the database
There are details on this site about how to programmatically activate and deactivate a plugin. Here is a snippet:
function toggle_plugin() {
// Full path to WordPress from the root
$wordpress_path = '/full/path/to/wordpress/';
// Absolute path to plugins dir
$plugin_path = $wordpress_path.'wp-content/plugins/';
// Absolute path to your specific plugin
$my_plugin = $plugin_path.'my_plugin/my_plugin.php';
// Check to see if plugin is already active
if(is_plugin_active($my_plugin)) {
// Deactivate plugin
// Note that deactivate_plugins() will also take an
// array of plugin paths as a parameter instead of
// just a single string.
deactivate_plugins($my_plugin);
}
else {
// Activate plugin
activate_plugin($my_plugin);
}
}
For everyone who has a plugin acting weird
The easiest way to regain access to your site when being locked out after deactivating, activating, installing, updating a plugin is:
Go to your webhost adminpanel (Cpanel, DirectAdmin)
Go to Files (Filemanager)
Go to //wp-content/ and rename your "plugins" folder to something else for instance "plugins_off"
Go to your WP-admin. You will have access again but no plugins visible.
Go back to your webhost adminpanel and rename "plugins_off" back to "plugins".
Now your plugins will all be listed again in WP-admin, but all deactivated.
Take it from there.
There is no need to add PHP code.
Like RST wrote: No need for coding to restore site that crashed after you deactivate a plugin. There's a good reason the site crashed because other plugins depended on that deactivated plugin (like WooCommerce).
The easiest way to restore the site and gain access to WP admin is simply to rename the plugins folder, refresh the page, go back and rename the folder back to "plugins" then hit refresh again. All plugins will be back as before only they are all deactivated. Now all you need to do is to activate them again. Do it one by one to be sure nothing else crashes.
Here is working code
(just uncomment "activate" line):
function MY_toggle_plugins() {
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
$temp_files1 = glob(WP_PLUGIN_DIR.'/*');
$activated=array();
$already_active=array();
foreach($temp_files1 as $file1){
if(is_dir($file1)) {
$temp_files2 = glob($file1 . '/*');
foreach($temp_files2 as $file2){
if(is_file($file2) && stripos(file_get_contents($file2),'Plugin Name:')!==false) {
$plugin_name_full=basename(dirname($file2)).'/'.basename($file2);
if(is_plugin_active($plugin_name_full)) {
array_push($already_active, $plugin_name_full);
//deactivate_plugins($plugin_name_full);
}
else{
array_push($activated, $plugin_name_full);
//activate_plugin($plugin_name_full);
}
}
}
}
}
echo 'You have activated these plugins:<br/><br/>'.serialize($activated).'<br/><br/>These were already active:<br/><br/>'.serialize($already_active); exit;
}
//execute
MY_toggle_plugins();

Categories