wp_enqueue_style seems to fail for local resources - css

Or behaves in a different way, but I do not get it :( :( :(.
Let's see, I got this :
$stylesheets_path = get_template_directory_uri().'/core/css/';
$test_url= #fopen('https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css','r');
if ( $test_url !== false ) {
echo "REMOTE:: $stylesheets_path";
wp_enqueue_style( 'font-awesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css', false );
} else {
echo "LOCAL:: {$stylesheets_path}font-awesome.min.css";
wp_enqueue_style('font-awesome', $stylesheets_path . 'font-awesome.min.css', false);
}
The point is, no matter how hard I try to make the remote option fails or simply use directly the local one, this last one does never loads at all :(.
Whenever I simply try to load the local option just removing all that code above just leaving
$stylesheets_path = get_template_directory_uri().'/core/css/';
wp_enqueue_style('font-awesome', $stylesheets_path . 'font-awesome.min.css', false);
it is useless and the css never loads. However, when I echo the stylesheets_path.'font-awesome.min.css' it shows a valid url where indeed the resource is located and properly loaded if I browse it.
The remote option loads seamlessly , but the local one no way !
Getting nuts :(

Related

How to integrate Dropzonejs with wordpress media handler in frontend?

How can I integrate Dropzonejs file uploader library in wordpress front end just like the built in one and have the uploaded one available in my media library?
Dropzonejs is a very extensive javascript library that provides a lot of options to handle media uploading.
To integrate dropzonejs with wordpress the process is pretty straight forward. Assume the following piece of code is where you want to appear your uploader.
<div id="media-uploader" class="dropzone"></div>
<input type="hidden" name="media-ids" value="">
Having a class dropzone will automatically attach the dropzone event with the element. That will stop us from overriding default parameters. So we would like to disable the auto discover feature of the library.
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
Now we will use jQuery to bind our configuration with the element.
jQuery("#media-uploader").dropzone({
url: dropParam.upload,
acceptedFiles: 'image/*',
success: function (file, response) {
file.previewElement.classList.add("dz-success");
file['attachment_id'] = response; // push the id for future reference
var ids = jQuery('#media-ids').val() + ',' + response;
jQuery('#media-ids').val(ids);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
},
// update the following section is for removing image from library
addRemoveLinks: true,
removedfile: function(file) {
var attachment_id = file.attachment_id;
jQuery.ajax({
type: 'POST',
url: dropParam.delete,
data: {
media_id : attachment_id
}
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
});
In the code above what we have done is we attached dropzone with our element with some parameters-
url - location where we want to send our files to upload. I'll initialize the variable later.
acceptedFiles - since we are only interested in uploading images, we will limit the files to be attached only to images. You can find about more in the website of this library.
success - a callback that is fired when the file/image is uploaded successfully. It accepts two parameter the reference of the uploaded file itself and the response from the server. This is very important, here we stored the attachment id in our form. You can perform a validation here prior to store the id.
error - if the file failed to upload then you can perform any task here.
addRemoveLinks - add the remove file link below the preview panel, you can style it with your css.
removedfile - handles the operation while you click on the remove file link for an image in the preview panel. In this function we sent an ajax call to our server to remove the image from the library
Of course there are a lot of option available, but I found these are the most basic parameters I required to setup my drag-n-drop media uploader.
Now the most important thing is to decide about the file uploader url. You can have a custom file where you would want to process the operation. But I found another way.
From this question and the answer I found using admin-post.php file is pretty amazing.
Many people complained about this admin-post.php, so think sticking to the wp_ajax.php is the best option.
So I initialized the drophandler variable prior to my dropzone initialization as follows-
wp_enqueue_script('dropzone','path/to/dropzone', array('jquery'));
wp_enqueue_script('my-script','path/to/script',array('jquery','dropzone'));
$drop_param = array(
'upload'=>admin_url( 'admin-ajax.php?action=handle_dropped_media' ),
'delete'=>admin_url( 'admin-ajax.php?action=handle_deleted_media' ),
)
wp_localize_script('my-script','dropParam', $drop_param);
Now we are ready to send our images to the server. Here we will add some php code whether in the theme's function.php file or in our plugin file, but we need to be assured that it is loaded.
The following function will take care of the uploading the image and saving as an attachment in the library.
add_action( 'wp_ajax_handle_dropped_media', 'handle_dropped_media' );
// if you want to allow your visitors of your website to upload files, be cautious.
add_action( 'wp_ajax_nopriv_handle_dropped_media', 'handle_dropped_media' );
function handle_dropped_media() {
status_header(200);
$upload_dir = wp_upload_dir();
$upload_path = $upload_dir['path'] . DIRECTORY_SEPARATOR;
$num_files = count($_FILES['file']['tmp_name']);
$newupload = 0;
if ( !empty($_FILES) ) {
$files = $_FILES;
foreach($files as $file) {
$newfile = array (
'name' => $file['name'],
'type' => $file['type'],
'tmp_name' => $file['tmp_name'],
'error' => $file['error'],
'size' => $file['size']
);
$_FILES = array('upload'=>$newfile);
foreach($_FILES as $file => $array) {
$newupload = media_handle_upload( $file, 0 );
}
}
}
echo $newupload;
die();
}
The following action take care of the deletion of the media element. Second parameter of wp_delete_attachment() function allows us to decide whether we want to trash the image or completely delete it. I wanted to delete it completely so passed true.
add_action( 'wp_ajax_handle_deleted_media', 'handle_deleted_media' );
function handle_deleted_media(){
if( isset($_REQUEST['media_id']) ){
$post_id = absint( $_REQUEST['media_id'] );
$status = wp_delete_attachment($post_id, true);
if( $status )
echo json_encode(array('status' => 'OK'));
else
echo json_encode(array('status' => 'FAILED'));
}
die();
}
This will return the attachment_id in the response and we'll get it in the success function. In the media_handle_upload( $file, 0 ); I passed the reference of the file and a 0 because I didn't wanted to assign the media with any post yet (0 for no post, but if you want to assign then pass the post ID here. More reference in the codex.)
This is all for uploading media in wordpress.
Note: I haven't completed the removing uploaded file part. I'll complete this in a moment.
UPDATE
The post is updated. Now we can remove uploaded media elements from the uploader container. Thanks to this question and the answer I could figure out the actual process.
Those who are having problems getting this to work for non-admin users; please use admin-ajax.php instead of admin-post.php.
I had faced a strange issue that admin-post.php would work for non-admin users on my local server; but my live server refused to let non-admins upload files. php would echo entire page instead of the echoed value.
I replaced admin-post.php with admin-ajax.php and uploads work super cool.
I hope this helps.
The solution added to this post is incorrect unless I've misunderstood the question. Basically the solution won't work for anyone who isn't logged in as an admin. It took me 30 minutes to work it out plus the solution for removing images doesn't delete it from the media library.

Wordpress 3.8.2 Appends ?ver=3.8.2 to filenames

I'm working on a WordPress site and suddenly all our plugins are malfunctioning. Inspect Elements shows the following:
GET http://example.com/wp-content/plugins/ninja-forms/css/qtip.css?ver=3.8.2 404 (Not Found) (index):295
GET http://example.com/wp-content/plugins/ninja-forms/js/dev/word-and-character-counter.js?ver=3.8.2 404 (Not Found) (index):299
GET http://example.com/wp-content/plugins/ninja-forms/css/ninja-forms-display.css?ver=3.8.2 404 (Not Found) (index):294
GET http://example.com/wp-content/plugins/ninja-forms/css/jquery.rating.css?ver=3.8.2 404 (Not Found) (index):296
GET http://example.com/wp-content/plugins/ninja-forms/js/min/ninja-forms-display.min.js?ver=3.8.2 404 (Not Found)
These files are all set to 755 and do exist on our server. Can anyone help us figure out why ?ver=3.8.2 is appended and how to remove it?
That's added by WordPress as a way of versioning the scripts. It's intended to be used as a cache buster if you update a stylesheet/script file but don't change the name. You can tell WordPress to not do this by filtering it out. Add this to functions.php or a plugin.
add_filter( 'style_loader_src', 'remove_versions_from_scripts_and_stylesheets', 999 );
add_filter( 'script_loader_src', 'remove_versions_from_scripts_and_stylesheets', 999 );
function remove_versions_from_scripts_and_stylesheets( $src ) {
if ( strstr( $src, 'ver=' ) ) {
$src = remove_query_arg( 'ver', $src );
}
return $src;
}
Keep in mind this is just going to remove the version at the end, there may be a bigger issue. If those files do exist on the server, the version thing wouldn't actually prevent them from loading.

Wordpress get plugin directory

Is there any function that would return the full path of my plugin in WordPress?
Example is
path/wp-contents/plugins/myplugin
I have tried plugin_dir_path(__FILE__) but returns the current dir.
I would suggest to use a WordPress internal constant to solve this case:
$my_plugin = WP_PLUGIN_DIR . '/my-plugin';
if ( is_dir( $my_plugin ) ) {
// plugin directory found!
}
Alternative
The other valid alternative is to compute the path from the URL which is more complex/confusing. I would not use this code:
$plugins_url = plugins_url();
$base_url = get_option( 'siteurl' );
$plugins_dir = str_replace( $base_url, ABSPATH, $plugins_url );
// Now $plugins_dir is same as the WP_PLUGIN_DIR constant.
$my_plugin = $plugins_dir . '/my-plugin';
My opinion in this case is: Use the constant WP_PLUGIN_DIR
Yeah as per description of plugin_dir_path it will give you current plugin file path. But as per what you asking here you can do something like below unfortunately no direct way,
$plugin_dir = ABSPATH . 'wp-content/plugins/plugin-folder/';
Edit: 18-09-2021
The best practice is to use with latest version is WP_PLUGIN_DIR as follow:
$plugin_dir = WP_PLUGIN_DIR . '/plugin-folder';
Code For Plugin Root Path
$dir = plugin_dir_path( __FILE__ );
// Example: /home/user/var/www/wordpress/wp-content/plugins/my-plugin/
Code for plugin path
echo WP_PLUGIN_DIR.'/plugin-name';
plugins_dir_path() is a misnomer.
It will always return the path to the current file.
Link to the codex:
https://developer.wordpress.org/reference/functions/plugin_dir_path/#more-information
It is a wrapper for trailingslashit( dirname( $file ) );.
The “plugin” part of the name is misleading – it can be used for any file, and will not return the directory of a plugin unless you call it within a file in the plugin’s base directory.
It is actually synonym for the trailingslashit() function.
IF the current file is in the plugins directory, then yes, the function returns the path of the current file.
However, if you call this function from a file inside any other directory, then current file is not in the plugins directory, and thus it will does NOT return the path to the plugins directory. It does always return the path to the current file, but without a trailing slash.
Most of the answers here are incorrect, or are only "sometimes" correct. Those answers will only work as they say IF your file happens to already be located in the plugins directory! In all other cases they will give you a misleading result: the path to your current file.
It is more likely that your file is in a *subdirectory *of the plugins folder.
If this is the case, this codex shows you how to create a URL to the current file:
https://codex.wordpress.org/Function_Reference/plugins_url
If you are using the plugins_url() function in a file that is nested inside a subdirectory of your plugin directory, you should use PHP's dirname() function:
<?php
echo '<img src="' . plugins_url( 'images/wordpress.png', dirname(__FILE__) ) . '" > ';
?>
You would then need to remove your file name to get the path.
Or use ``
ANSWER:
These solutions solutions are independant of where the file of your calling function is located. If your file is located in the plugins folder, or a subdirectory of it, then the above options would work. Otherwise, you'll need to resort to something along the lines of:
WP_PLUGIN_DIR
WordPress does have a constant defined, for the Plugins' folder:
Codex: https://codex.wordpress.org/Determining_Plugin_and_Content_Directories
Constants
WordPress makes use of the following constants when determining the path to the content and plugin directories. These should not be used directly by plugins or themes, but are listed here for completeness.
WP_CONTENT_DIR // no trailing slash, full paths only
WP_CONTENT_URL // full url
WP_PLUGIN_DIR // full path, no trailing slash
WP_PLUGIN_URL // full url, no trailing slash
// Available per default in MS, not set in single site install
// Can be used in single site installs (as usual: at your own risk)
UPLOADS // (If set, uploads folder, relative to ABSPATH) (for e.g.: /wp-content/uploads)
Or, If you can guarantee that the plugins folder is located in the normal place for a WordPress install, i_a's answer above answer above will work, no matter what directory your file (that you want to call this function from) is in.
Please see his more complete post in this thread, but so as to not have a "link only answer", I'll include here that it Essentially, it boils down to using the following (and turning it into a function):
$plugins_root = WP_CONTENT_DIR . '/plugins';
Or M07's post, also in this thread, here: https://stackoverflow.com/a/28525164/5411817
Kinda late to this party, but just in case some else stumbles upon this.
plugin_dir_path(__FILE__) will always return the current path (where the file calling it is located).
If you want the root, use the code below:
plugin_dir_path( dirname( __FILE__ ) )
You can then define a constant:
define( 'YOUR_PLUGIN_DIR', plugin_dir_path( dirname( __FILE__ ) ) );
require_once YOUR_PLUGIN_DIR . 'includes/admin-page.php'
require_once YOUR_PLUGIN_DIR . 'admin/classes.php'
You can define a constant into your main PHP file. It should be at the root of your plugin folder.
The file should be here : .../wp-content/plugins/plugin-folder/my-plugin.php
You can add into the file this line.
define( 'MYPLUGIN__PLUGIN_DIR_PATH', plugins_url( '', __FILE__ ) );
After you can use your new constant anywhere in your plugin.
public function Test()
{
$folder2 = MYPLUGIN__PLUGIN_DIR_PATH . '/folder1/folder2/';
// $folder2 = .../wp-content/plugins/plugin-folder/folder1/folder2/
}
I hope it will help someone.
As noted on the section Common Usage of Plugins Url function reference page, that's what worked for me:
If you are using the plugins_url() function in a file that is nested inside a subdirectory of your plugin directory, you should use PHP's dirname() function:
echo plugins_url('', dirname(__FILE__) );
The output for this was:
http://domain/app/wp-content/plugins/my-plugin
The file that called the function was my functions.php inside includes, so the complete path to my file was:
http://domain/app/wp-content/plugins/my-plugin/includes/functions.php
I will suggest following code. if you are accessing this function from any subfolder.
plugins_url( 'images/logo.png' , dirname(__FILE__ ));
Unfortunately, most of the answers here seem to forget about one important thing.
In addition to the plugins dir, plugins might be also in the Must-use plugins (mu-plugins) directory
Because of that, we need to check multiple directories.
An example function to do this:
function get_plugin_dir_path($pluginFolderName){
if ( defined( 'WPMU_PLUGIN_DIR' ) && file_exists( trailingslashit( WPMU_PLUGIN_DIR ) . $pluginFolderName ) ) {
return trailingslashit( WPMU_PLUGIN_DIR ) . $pluginFolderName;
} elseif ( defined( 'WP_PLUGIN_DIR' ) && file_exists( trailingslashit( WP_PLUGIN_DIR ) . $pluginFolderName ) ) {
return trailingslashit( WP_PLUGIN_DIR ) . $pluginFolderName;
}
return false;
}
plugin_dir_path( __FILE__ ) will give you plugin path of current file.
this is mean if you call this function like that inside "your_plugin_dir/sub_dir/file.php"
will return "your_plugin_dir/sub_dir/"
if you want to get the ROOT of your plugin directory, just change __FILE__ to __DIR__
plugin_dir_path( __DIR__ )
Here is a solution, when you are not inside the plugin root:
As of now with 4.7.5, WordPress does not have a get_plugins_root() function like there is a get_theme_root() function. This is probably because you really shouldn't ever need to modify plugins from your theme, and the plugins root directory never changes.
However, it can be useful if you need to programmatically affect plug-ins while developing themes.
Simply, as WP does for the theme root:
$plugin_root = WP_CONTENT_DIR . '/plugins';
Or, if you need a function, why not just do it the same way WordPress does it for the theme root?
Just make a copy of the function get_theme_root() from wp-includes/theme.php and paste it into your theme's functions.php file, rename the function to get_plugins_root(), simplify it, and change 'theme' to 'plugins' in the function...
get_plugins_root() {
$plugins_root = WP_CONTENT_DIR . '/plugins';
/**
* Filters the absolute path to the plugins directory.
*
* #since now
*
* #param string $plugins_root Absolute path to plugins directory.
*/
return apply_filters( 'plugins_root', $plugins_root );
}
With the path, you can now add the plug-ins folder name that you wish to affect.
$the_plugin_root = get_plugins_root()."/the-plugin-name/";
My solution has been to use inside plugin_dir_path DIR
plugin_dir_path( __DIR__ ) . $path_inside_plugin_folder;
The above should give you the absolute path to your plugin folder on the server, then you can load your variable with any file within your plugin folder
As mentioned by #tsl143 the function plugins_url() is what you want, along with the __FILE__ magic constant. If you call it from a file inside your plugin folder it will refer to that folder.
Example:
For the directory:
echo plugins_url( '' , __FILE__ );
//outputs: http://www.example.com/wp-content/plugins/my-plugin
For a file or subdirectory in your plugin directory:
echo plugins_url( 'images/logo.png' , __FILE__ );
//outputs: http://www.example.com/wp-content/plugins/my-plugin/images/logo.png
You can gain it by using this method
plugin_dir_url( __DIR__ )
The other solutions either won't work if called from a sub-directory of your plugin or they require that you to hard code your plugin's directory name or you need to define a global variable.
My solution uses a function that can be placed in any directory of your plugin without requiring that you to hard code something.
function get_my_plugin_root_dir()
{
// WP_PLUGIN_DIR will have something like "/home/michael/public_html/wp-content/plugins"
// __DIR__ will have something like "/home/michael/public_html/wp-content/plugins/my-plugin-folder/the-dir-being-called-from
// First, we remove WP's root plugin path from our __DIR__ path.
$path_to_this_files_dir_without_wp_plugin_dir = str_replace(WP_PLUGIN_DIR, '', __DIR__);
// Now, we're left with only our plugin's path, which looks like
// this: "/my-plugin-folder/the-dir-being-called-from"
// Next, we discard any sub-directories that are included with our
// plugin's path and keep the first directory in the path, our
// plugin's directory name.
$plugin_directory_name_only = explode(DIRECTORY_SEPARATOR, $path_to_this_files_dir_without_wp_plugin_dir)[1];
// Now $plugin_directory_name_only has "my-plugin-folder"
// Lastly, we build the plugin's complete root path using
// WP's root plugin directory and our plugin's root dir name.
return WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $plugin_directory_name_only;
}
As of now, there isn't any function that will return only the full path of your plugin's base directory.
However, the constant WP_CONTENT_DIR is used by WordPress for just about that. But, even though, WordPress uses this constant, they warn us not to use it directly in our plugins or themes. That's because it can cause issues like when users change or rename their plugin's directory from the default one.
Using the plugin_dir_path() function will return the path of the file's directory from where it is called. So, if you call this function from a PHP file that is inside a subfolder of your plugin, it will return the path of that subfolder's directory and not your plugin's base directory.
Answer
Now, as a workaround, we can define a constant in a PHP file that is directly inside the plugin's base directory and then set its value to the result of calling plugin_dir_path( __FILE__ ). This way, we will be able to use that constant anywhere in the plugin to get the full path of the plugin's base directory.
So, open a PHP file located directly in your plugin's base directory. For instance:
../wp-content/plugins/myplugin/myplugin.php
Then, define a constant by setting its value to the result of calling plugin_dir_path() function. For instance:
define( 'MYPLUGIN_PLUGIN_DIR_PATH', plugin_dir_path( __FILE__ ) );
This constant now holds the path of your plugin's root directory. So, now, if you echo that constant from any file located in any directory of your plugin like this:
echo MYPLUGIN_PLUGIN_DIR_PATH;
It will print something like this:
/home/example.com/public_html/wp-content/plugins/myplugin/
This solution wasn't available when the original answer was accepted.
If the current file is two folders down into the plugin path, use this:
$plugin_path = plugin_dir_path(dirname(__FILE__, 2));
$plugin_url = plugin_dir_url(dirname(__FILE__, 2));
Note the number as the second parameter on dirname(), available since PHP v7.0.0.
The technique to use a constant works with this too, this time outside of the root-level plugin.php :
// from pluginname/src/API/Common/Constants.php
define( 'MYPLUGIN_PLUGIN_DIR_PATH', plugin_dir_path(dirname(__FILE__, 3)) );
Note this comment on the PHP Manual site:
Dirname likes to mess with the slashes.
So I normalize the path to avoid double slashes, and slashes that are wrong for the current OS:
$normalized = wp_normalize_path( $plugin_path . '/' . $required_file);
if (file_exists($normalized))
require_once $normalized;
else
die(__('Required file does not exist') . ": $normalized");
As others have stated, using plugin_dir_path(__FILE__) works to get the directory of your plugin if used within the main plugin file (e.g. plugins/myplugin/myplugin.php.
But what if you want to know the plugin directory from another file in your plugin? Well what I like to do is define a constant in my main plugin file like this;
// plugins/myplugin/myplugin.php
define('MYPLUGIN_PATH', plugin_dir_path(__FILE__));
Then in other php files within your plugin, you can use MYPLUGIN_PATH (a constant) anywhere you like, without knowing the directory structure!
rather than take the advice of someone who's not using your server (and continue guessing at it...)
why not just load a so-called "Classic" theme, and see what you get?
You're either going to get a relative, or an absolute path. It's not random. figure it out. if you don't like the output, change the function/ args. If you don't know the function names, Install Visual Studio Code, and one of the several WordPress autocomplete / intellisense plugins. It basically writes the code for you.
e.g. ./wp-content/themes/classic/footer.php
wp_footer();
echo '<br><strong>plugin_dir_url(dirname(__FILE__))</strong><br> '. plugin_dir_url(dirname(__FILE__));
echo '<br><strong>plugins_url()</strong><br> '. plugins_url();
echo '<br><strong>__FILE__</strong><br> ' .__FILE__ .'<br>';
?>
go from there.

Must manually load PHP ActiveRecord models

I'm drawing a blank. I have code working locally (which is MAMP). When moving to a nginx ubuntu box (running php-fpm), for some reason, phpactiverecord is acting up.
I finally traced it down to this - All of my model classes, I have to load manually. If I add a require_once() underneath my code, then it works fine. If I don't, then I get errors like:
PHP Fatal Error: Class not found ... on the models I've created..
Does anyone have ANY idea what direction I could troubleshoot this in? I checked permissions to the models folder (which is not in the public root), echo'd out the path that is sent over to cfg->set_model_directory is correct, etc..
This sound like a nginx or php thing? I'm guessing nginx since this works on my MAMP?
Doesn't work:
ActiveRecord\Config::initialize(
function ($cfg) {
$cfg->set_model_directory(BASE_PATH . '/models');
$cfg->set_connections(
array(
'development' => 'mysql://blah:removed#localhost/com_dbname'
)
);
}
);
Works:
ActiveRecord\Config::initialize(
function ($cfg) {
$cfg->set_model_directory(BASE_PATH . '/models');
$cfg->set_connections(
array(
'development' => 'mysql://blah:removed#localhost/com_dbname'
)
);
}
);
require_once(BASE_PATH . '/models/model1.php');
require_once(BASE_PATH . '/models/model2.php');
Update
Adding in actual code to help identify issue:
require_once ('../lib/php-activerecord/ActiveRecord.php');
ActiveRecord\Config::initialize(
function ($cfg) {
$cfg->set_model_directory('/var/www/uc1/models');
$cfg->set_connections(
array(
'development' => 'mysql://test_usr:test_pwd#localhost/test_db'
)
);
}
);
require_once ('/var/www/uc1/models/ucurls.php'); //Name of model file. Must manually include to get this to work on my nginx server.
$_record = UCUrls::find_by_urlkey('example.com/123');
echo "urlkey=" . $_record->urlkey;
I solved this issue in windows adding a line in the file ActiveRecord.php,
in the function activerecord_autoload($class_name)
at the line 39 or 40
$file = "$root/$class_name.php";
//add this line
$file = strtolower($file);
Set trace in ActiveRecord.php too look where are ActiveRecord is searching for models.
But I think your issue is in filesystem - Mac OS X by default uses Case Insensitive filesystem, while Ubuntu's Case Sensitive filesystem.
So your model UCUrls should be in file /var/www/uc1/models/UCUrls.php, not in /var/www/uc1/models/ucurls.php

Drupal rules php action

I am experimenting with the Rules module for the first time and I am attempting to redirect my users with some simple php code as below:
drupal_set_message('testing');
drupal_goto('node/3');
The first line of code executes but the second, which should direct my users to node/3, does not have the desired effect.
How can I get this redirecting feature working?
It's most likely because you have ?destination=some/path in the page URL, these lines in drupal_goto() cause any path you pass to the function to be overwritten by whatever's in the URL:
if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
$destination = drupal_parse_url($_GET['destination']);
$path = $destination['path'];
// ...
You can probably get around it simply by changing your code to this:
if (isset($_GET['destination'])) {
unset($_GET['destination']);
}
drupal_goto('node/3');
If that doesn't work try adding this line before drupal_goto:
drupal_static_reset('drupal_get_destination');
which will reset the static cache for the drupal_get_destination() function, which also gets involved in this process at some point (I think).
If all else fails, go old school:
$path = 'node/3';
$options = array('absolute' => TRUE);
$url = url($path, $options);
$http_response_code = 302;
header('Location: ' . $url, TRUE, $http_response_code);
drupal_exit($url);
That's pretty much nicked straight from the drupal_goto() function itself and will definitely work.

Resources