Naming Drupal 7 template files based on url - drupal

If I have a page whose url alias is "/api/user/create", how can I name a template file based on the url such as "page-api-user-create.tpl.php".

You need to name it:
page--api--user--create.tpl.php
(note double dashes in the file name).
See http://drupal.org/node/1089656 for more info.

You can set up a page level template file to reflect the url, as was explained by Maciej Zgazdaj.
To do the same with a node level template file you have to add this to your template.php file:
function YOURTHEME_preprocess_node(&$variables) {
$url = str_replace("-", "", $variables['node_url']);
$urlParts = explode("/", $url);
unset($urlParts[0]);
if($urlParts[1] !== false) {
$out = array();
$sug = "node";
foreach($urlParts as $val) {
$sug .= "__".$val;
$out[] = $sug;
}
$variables['theme_hook_suggestions'] =
array_merge($variables['theme_hook_suggestions'], $out);
}
}
Replace YOURTHEME with .. well your theme. Check the offered suggestions with devel_themer.

Related

Insert PHP file in functions.php then echo variables from that file in Wordpress

After trying to find a solution to this, I've decided I'm not bright enough. So, please help.
Here the idea: have a file (ip.php) detect the visitors' country/city, call it once in functions.php (or header.php), then echo/print variables from this ip.php file into the other Wordpress theme files (for example footer.php).
This is the ip.php content:
<?php
function getUserIP()
{
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
$_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
$user_ip = getUserIP();
require_once 'vendor/autoload.php';
use GeoIp2\Database\Reader;
$cityDbReader = new Reader('/html/nocache-ip/GeoLite2-City.mmdb');
$record = $cityDbReader->city($user_ip);
$country = $record->country->name;
?>
Using the following in the header.php works fine for the header:
require_once( ABSPATH . '/nocache-ip/ip.php' );
echo "\nYou came from $country\n";
The country, city names are displayed. But when trying to use the same code again in the footer.php, it doesn't work (Undefined variable: country).
So this is the issue. How can I make echo/print the visitor's country in other parts of the theme, while calling the ip.php only once?
I've read about having to make all this into a function, then add it to functions.php somehow and then calling the variables with country(); unfortunately this is above my head.
You can use include so that your function is available, example: <?php include 'yourfunctionpage.php';?>

Create file dynamically as File object and then publish

It's evidently a little more complicated to create a file dynamically in SS4
$folder = Folder::find_or_make('Cards');
$filename = 'myimage.jpg';
$contents = file_get_contents('http://example.com/image.jpg');
$pathToFile = Controller::join_links(Director::baseFolder(), ASSETS_DIR, $folder->Title, $filename);
file_put_contents($pathToFile, $contents);
$image = Image::create();
$image->ParentID = $folder->ID;
$image->Title = "My title";
$image->Name = $filename;
$image->FileFilename = 'Cards/' . $filename;
$image->write();
Member::actAs(Member::get()->first(), function() use ($image, $folder) {
if (!$image->isPublished()) {
$image->publishFile();
$image->publishSingle();
}
if (!$folder->isPublished()) {
$folder->publishSingle();
}
});
The above, creates the file as expected in /assets/Cards/myimage.jpg and publishes it fine
However all previews are blank, so it's obviously not finding the file:
Any idea what I missed in creating the Image object?
This should work:
$folder = Folder::find_or_make('Cards');
$contents = file_get_contents('http://example.com/image.jpg');
$img = Image::create();
$img->setFromString($contents, 'image.jpg');
$img->ParentID = $parent->ID;
$img->write();
// This is needed to build the thumbnails
\SilverStripe\AssetAdmin\Controller\AssetAdmin::create()->generateThumbnails($img);
$img->publishSingle();
FYI: $img->Filename no longer exists. An Image or File object have a File property, which is a composite field of type DBFile. This composite fields contains the filename, hash and a variant…
So you should use the composite field to address these fields.

Download multiple images in zip in Wordpress

I am working on my personal wordpress site that distribute images.
In single post page, I registered several images via ACF(Advanced Custom Fields) and I know how to get image path/filename through get_field ACF function.
I just googled then found this page, but how can I apply this technique to wordpress site?
Download multiple images into zip
Now I am stuck...
On single post page, place the url of download_zip.php file, where you will place all your code for creating zip.
On single post page:
Download ZIP
In variable 'model_id', place the post id of the single post.
Now create a download_zip.php file on the root of your wordpress setup, where wp-config.php file exists.
Here is the code of download_zip.php file.
<?php
/*File for downloading the gallery zip files*/
$post_id = $_GET['model_id'];
require_once('wp-blog-header.php');
require_once('/wp-admin/includes/file.php');
WP_Filesystem();
$files_to_zip = array();
$zip = new ZipArchive();
$title = get_the_title($post_id);
$destination = wp_upload_dir();
//var_dump($destination);
$destination_path = $destination['basedir'];
$DelFilePath = str_replace(" ","_",$title).'_'.$post_id.'_'.time().'.zip' ;
$zip_destination_path = $destination_path."/".$DelFilePath;
if(file_exists($destination_path."/".$DelFilePath)) {
unlink ($destination_path."/".$DelFilePath);
}
if ($zip->open($destination_path."/".$DelFilePath, ZIPARCHIVE::CREATE) != TRUE) {
die ("Could not open archive");
}
//this is only for retrieving Repeater Image custom field
$row1 = get_field('acf_field_name1',$post_id);
$row1 = get_field('acf_field_name2',$post_id);
$rows = array($row1,$row2);
if($rows) {
foreach($rows as $row): ?>
<?php
$explode = end(explode("uploads",$row));
$index_file = array($destination_path,$explode);
$index_file = implode("",$index_file);
$new_index_file = basename($index_file);
$zip->addFile($index_file,$new_index_file);
endforeach;
}
$zip->close();
if(file_exists($zip_destination_path)) {
send_download($zip_destination_path);
}
//The function with example headers
function send_download($file) {
$basename = basename($file);
$length = sprintf("%u",filesize($file));
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.$basename.'"');
header('Content-Transfer-Encoding: binary');
header('Pragma: public');
header('Content-Length: ' . $length);
set_time_limit(0);
ob_clean();
flush();
readfile($file); // "Outputs" the file.
unlink($file);
}
?>
Please modify this code according to your requirement such as get_field(), place your image field name inside it, & define your upload directory, so that you can break the url in $explode variable for defining path of image in $index_file variable.
And please also check your destination path stored in $destination_path variable is correct or not.
Hope, this may be helpful to you.

Creating a folder with PHP using input values

I am trying to create a folder in PHP, by calling a value. Creating one works fine. But once I try calling the value instead and concatenating it with the existing folder, it won't work. I have tried several things.
For example, I want to be able to have someone type in a name for their folder in an input field, so that they may choose what will the name of the folder be. For example, they could write on the website "mypics", and when I access my ftp program, I would now see images/mypics/
As for the HTML portion, I have this (check the fiddle for the rest of it http://jsfiddle.net/GF6qk/ ):
<input type="text" id="folder" name="folder">
As for the PHP aspect, I have the following
<?php
// We're putting all our files in a directory called images.
// Desired folder structure
$folder = $_POST['folder'];
$dirPath = 'images/'.$folder;
$result = mkdir($dirPath, 0755);
if ($result == 1) {
echo $dirPath . " has been created";
} else {
echo $dirPath . " has NOT been created";
}
//$image_name = '';
$uploaddir = 'images';
// The posted data, for reference
$file = $_POST['value'];
$name = $_POST['name'];
// Get the mime
$getMime = explode('.', $name);
$mime = end($getMime);
// Separate out the data
$data = explode(',', $file);
// Encode it correctly
$encodedData = str_replace(' ','+',$data[1]);
$decodedData = base64_decode($encodedData);
?>
I have also used this line (which was the original line I tried in the above code, which I then changed).
$dirPath = 'images/$folder';
try this and it is working
$folder = $_POST['folder'];
$dirPath = 'images/'.$folder;
$result = mkdir($dirPath);
if ($result == '1') {
echo $dirPath . " has been created";
} else {
echo $dirPath . " has NOT been created";
}
<input type="text" id="folder" name="folder">
Are you receiving any errors? If so, what are they? Does the "images" folder already exist? I tried your exact code, and it worked if the images folder already exists.....

Drupal Page Template based on url alias

I want to create an drupal page Template depending on the url alias.
Her my current situation:
I create a page named test, the url alias is test, too.
The page template, based on this docu - http://drupal.org/node/1089656 is: page--test.tpl.php.
I cleaned the drupal them cache, but there is still the default page template shown for this page.
What could be the error?
page--test.tpl.php doesn't work because Drupal is using the real path of page--node--#.tpl.php. To get Drupal to recognize aliased paths, you have to add the aliased path as part of the theme suggestions like so:
function MYMODULE_preprocess_page(&$vars, $hook) {
// only do this for page-type nodes and only if Path module exists
if (module_exists('path') && isset($vars['node']) && $vars['node']->type == 'page') {
// look up the alias from the url_alias table
$source = 'node/' .$vars['node']->nid;
$alias = db_query("SELECT alias FROM {url_alias} WHERE source = '$source'")->fetchField();
if ($alias != '') {
// build a suggestion for every possibility
$parts = explode('/', $alias);
$suggestion = '';
foreach ($parts as $part) {
if ($suggestion == '') {
// first suggestion gets prefaced with 'page--'
$suggestion .= "page--$part";
} else {
// subsequent suggestions get appended
$suggestion .= "__$part";
}
// add the suggestion to the array
$vars['theme_hook_suggestions'][] = $suggestion;
}
}
}
}
Source: http://groups.drupal.org/node/130944#comment-425189

Resources