So. I created a custom WordPress taxonomy. And I have multiple posts that use that taxonomy with various terms under this taxonomy. What I'm trying to get WordPress to do is spit out all the taxonomy terms from all the posts. I'm going to stick each of them inside a rel="" tag so I can get a little fancy with jQuery.
I accomplished this with plain old WordPress tags like this:
<?php
$posttags = get_tags();
if ($posttags) {
foreach($posttags as $tag) {
echo '<label><input type="checkbox" rel="' . $tag->slug . '">' . $tag->name .
'</label>';
}
}
?>
It works perfectly. Makes a checkbox and label for each tag. But now I need these custom taxonomy terms instead.
I've been fiddling with:
$categories = get_terms('Year-taxonomy', 'orderby=name&hide_empty=0');
$cats = object_to_array($categories);
Not working so far. Am I on the right track?
Not well versed with the WordPress Codex, but managed to figure it out.
First off there's the function:
function get_custom_terms($taxonomies, $args){
$args = array('orderby'=>'asc','hide_empty'=>true);
$custom_terms = get_terms(array($taxonomies), $args);
foreach($custom_terms as $term){
echo 'Term slug: ' . $term->slug . ' Term Name: ' . $term->name;
}
}
Then the function call wherever need:
<?php get_custom_terms('your_custom_taxonomy_name'); ?>
Function call must be same as function name:
get_custom_terms('your_custom_taxonomy_name');
Related
In CakePHP 4.x I'm having some trouble with the mailer() function, specifically passing variables from my controller to a template.
I need a user to be able to receive an email with a list of items. I'm able to use ajax to send an array to my controller, but I can't get the controller to pass the variables to the email template. I'm getting the email but not the dynamic content and I just can't get it to work via setViewVars.
My controller function:
public function bar(): void
{
if( $this->request->is('ajax') ) {
$this->request->allowMethod('ajax');
$foo = $this->request->getQuery('data');
// data is a stringified array
$mailer = new Mailer("default");
$mailer->viewBuilder()->setTemplate('default','default');
$mailer
->setEmailFormat('html')
->setFrom(['email#email.com' => 'Comparaciones'])
->setTo('email#email.com')
->setSubject('About')
>setViewVars($foo)
->send();
// ->deliver() doesn't work either
}
}
My template:
// standard cakephp default template
$content = explode("\n", $content);
foreach ($content as $line) :
echo '<p> ' . $line . "</p>\n";
endforeach;
I'm probably tripping up with something simple, I just can't get the array into the template. Any help much appreciated!!!
I've developed a CakePHP plugin that allows the site administrator to define custom reports as a list of SQL queries that are executed and the results displayed by a .ctp template.
Now I need to allow the administrator to edit the template, stored in the DB together with the report.
Therefore I need to render a template that is inside a string and not in a .ctp file and I could not find anything in the core that helps.
I considered initially the approach to write the templates in .ctp files and load them from there, but I suspect this solution is rigged with flaws re: the location of the files and related permissions.
A better solution seems to override the View class and add a method to do this.
Can anyone suggest a better approach ?
P.S. Security is not a concern here, since the administrator is basically a developer without access to the code.
In CakePHP 2.0:
The View::render() method imports the template file using
include
The include statement includes and evaluates the specified file.
The evaluated template is immediately executed in whatever scope it was included. To duplicate this functionality, you would need to use
eval()
Caution: The eval() language construct is very dangerous because it
allows execution of arbitrary PHP code. Its use thus is discouraged.
If you have carefully verified that there is no other option than to
use this construct, pay special attention not to pass any user
provided data into it without properly validating it beforehand.
(This warning is speaking to you, specifically)
...if you wish to continue... Here is a basic example of how you might achieve this:
$name = 'world';
$template = 'Hello <?php echo $name ?>... <br />';
echo $template;
// Output: Hello ...
eval(' ?>' . $template . '<?php ');
// Output: Hello world...
Which is (almost) exactly the same as:
$name = 'world';
$template = 'Hello <?php echo $name ?>... <br />';
file_put_contents('path/to/template.php', $template);
include 'path/to/template.php';
Except people won't yell at you for using eval()
In your CakePHP application:
app/View/EvaluatorView.php
class EvaluatorView extends View
{
public function renderRaw($template, $data = [])
{
if (empty($data)) {
$data = $this->viewVars;
}
extract($data, EXTR_SKIP);
ob_start();
eval(' ?>' . $template . '<?php ');
$output = ob_get_clean();
return $output;
}
}
app/Controller/ReportsController.php
class ReportsController extends AppController
{
public function report()
{
$this->set('name', 'John Galt');
$this->set('template', 'Who is <?php echo $name; ?>?');
$this->viewClass = 'Evaluator';
}
}
app/View/Reports/report.ctp
// Content ...
$this->renderRaw($template);
Alternatively, you may want to check out existing templating engines like: Mustache, Twig, and Smarty.
Hmmm.. Maybe create a variable that will store the generated code and just 'echo' this variable in ctp file.
I had similar problem (cakephp 3)
Controller method:
public function preview($id = null) {
$this->loadModel('Templates');
$tempate = $this
->Templates
->findById($id)
->first();
if(is_null($template)) {
$this->Flash->error(__('Template not found'));
return $this->redirect($this->referer());
}
$html = $template->html_content;
$this->set(compact('html'));
}
And preview.ctp is just:
<?= $html
I'm fairly new to certain programming techniques. Very new to OOP and MVC in general. And I'm pretty sure this is my first StackOverflow question!
I've just downloaded CodeIgniter and have a little project for myself.
I have a list of files and folders on the server and would like to use opendir, readdir and closedir etc to list out them out on a web page in ul's and li's - I've done this in procedural before in a function but have no idea where to even begin with CodeIgniter.
Is there a Helper or Library that already does this? If not, what is the best method? Should I put my code in the model folder?
So confused!
I hope you have learned about MVC architecture already in past year :)
Now about your question. This helper or library you have asked for really exists. For the very same "problem" I have used directory helper and its function directory_map('relative/path/to/your/directory'). This function gets recursively content from your directory and sorts it into array like this
Array
(
[banner] => Array
(
[0] => banner1.jpg
[1] => banner2.jpg
[2] => banner3.jpg
[3] => banner4.jpg
)
[galerie] => Array
(
[0] => 0-PB083393.JPG
[1] => DSCN2897.JPG
[2] => DSCN2908.JPG
[3] => DSCN2917.JPG
[thumb] => Array
(
[0] => 0-PB083393_thumb.JPG
[1] => DSCN2897_thumb.JPG
[2] => DSCN2908_thumb.JPG
)
)
[0] => mapa.jpg
)
which is quite neat and you can use it in - for example - foreach cycle and add ul/li tags.
Probably this question is not relevant after one year, but I hope it could help others.
Ha. This is funny. I was looking for something else and stumbled on to my first ever CI question without realising it was me :D
I've come so far with CI in just less than a month.
I found Directory Helper - directory_map that basically puts your folder structure in to an array of arrays.
I them created a recursive function in the model that turns it in to a proper drop down menu... And when it's a file, it adds in an a href link to that file.
http://ellislab.com/codeigniter/user-guide/helpers/directory_helper.html
If I were doing this, I would:
(1) Create a Library class with a method that takes a directory name and returns an
array of files.
(2) In my controller, I would then load the library and use it to get the list of files for the folder of interest.
(3) I would then load a view while passing the array of file names to the view where
I would assemble the list.
Start by learning how to use the controller to load a view with data (start with a static array). Then learn how to create the library and integrate with your controller.
You might also read up about CodeIgniter's File Helper library unless you want to use the native PHP functions.
Also, learn about PHP unit testing.
I tend to use models for dealing with data from MySQL databases. In your case, you are dealing with information about your file system.
Good luck, CI is a good choice for a PHP/MySQL framework!
First, welcome to CodeIgniter. It rules. Now...
You need a controller function to actually process the directory, similar to this:
public function dir_to_array($dir, $separator = DIRECTORY_SEPARATOR, $paths = 'relative')
{
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value)
{
if (!in_array($value, array(".", "..")))
{
if (is_dir($dir . $separator . $value))
{
$result[$value] = $this->dir_to_array($dir . $separator . $value, $separator, $paths);
}
else
{
if ($paths == 'relative')
{
$result[] = $dir . '/' . $value;
}
elseif ($paths == 'absolute')
{
$result[] = base_url() . $dir . '/' . $value;
}
}
}
}
return $result;
}
Now you need to call that function to return the results, similar to:
$modules['module_files'] = $this->dir_to_array(APPPATH . 'modules');
This will put the results in a variable called $modules, which you can use in whichever way you want, typically put it in a view like this:
$this->load->view('folder/file', $modules);
If you provide an optional third parameter of TRUE to the load->view function, the result of that view will again be returned for you to use anywhere you like, otherwise it will be echoed out where you call it. The view may look something like this:
<?php
if (isset($module_files) && !empty($module_files))
{
$out = '<ul>';
foreach ($module_files as $module_file)
{
if (!is_array($module_file))
{
// the item is not an array, so add it to the list.
$out .= '<li>' . $module_file . '</li>';
}
else
{
// Looping code here, as you're dealing with a multi-level array.
// Either do recursion (see controller function for example) or add another
// foreach here if you know exactly how deep your nested list will be.
}
}
$out .= '</ul>';
echo $out;
}
?>
I have not checked this for syntax errors, but it should work fine. Hope this helps..
I have a Game model, view and controller, and a newgame action which creates a new game record. That works fine.
I then want to make that form data available to main_game_view.ctp either in the session, or as a passed-in-array (but not visible as a URL parameter). I don't mind if it's done on the session, or passed-in, whichever is the more efficient.
I've tried various different combos of set this, write that, pass the other, but nothing's worked so far. Here's my code as it stands after my latest failure. The GamesController newgame action:
public function newgame() {
if ($this->request->is('post')) {
$this->Game->create();
$this->Session->write('Game',$this->request->data);
if ($this->Game->save($this->request->data)) {
// Put the id of the game we just created into the session, into the id field of the Game array.
$this->Session->write('Game.id',$this->Game->getLastInsertID());
$this->redirect(array('action' => 'main_game_view'));
} else {
$this->Session->setFlash('There was a problem creating the game.');
}
}
}
Writing the game id to the session works perfectly, I can see that in main_game_view when I read() it. But no matter where I put the session write for the request data, I can't find it in the main_game_view.
Similarly, if I try to pass, well, anything into the redirect, I can't find it in either the main_game_view action, or the main_game_view view itself.
Currently my main_game_view action is just an empty function, but I couldn't find anything in there after trying to pass the data via redirect.
Here's the main_game_view.ctp:
<?php debug($this->viewVars); ?>
<p><?php echo 'Game id: ' . $this->Session->read('Game.id') ?></p>
<p><?php echo 'Game name: ' . $this->Session->read('Game.game_name') ?></p>
Game.id is fine, but there's nothing in Game.game_name (which is a valid field name from the model. All my attempts to pass in variables have also failed, the debug line has only ever shown: array().
This seems so simple, having followed the CakePHP blog tutorial and adapting it to create/edit/delete game instances, but obviously something hasn't quite sunk in...
You dont have Game.game_new key in session just by writing: $this->Session->write('Game',$this->request->data); Obviously you have to do something like this in main_game_view:
<?php $game = $this->Session->read('Game'); ?>
<p><?php echo 'Game id: ' . $this->Session->read('Game.id') ?></p>
<p><?php echo 'Game name: ' . $game['Game']['game_name']; ?></p>
I developed a Content type of "Car Sales" with following fields:
Manufacturer
Model
Make
Fuel Type
Transmission (Manual/Automatic)
Color
Registered? (Yes/No)
Mileage
Engine Power
Condition (New/Reconditioned/Used)
Price
Pictures (Multiple uploads)
I have developed View of this Content Type to display list of cars. Now I want to develop a screen/view for individual Car Sale Record like this:
Apart from arranging fields, please note that I want to embed a Picture Gallery in between. Can this be achieved through Drupal 7 Admin UI or do I need to create custom CSS and template files? If I need to edit certain template files/css, what are those? I'm using Zen Sub Theme.
I would accomplish this by creating a page, and then creating a node template to accompany it. Start by creating a new node, and then record the NID for the name of the template.
Then, in your template, create a new file, and name it in the following manner: node--[node id].tpl.php
Then, in that file, paste in the following helper function (or you can put it in template.php if you're going to use it elsewhere in your site):
/**
* Gets the resulting output of a view as an array of rows,
* each containing the rendered fields of the view
*/
function views_get_rendered_fields($name, $display_id = NULL) {
$args = func_get_args();
array_shift($args); // remove $name
if (count($args)) {
array_shift($args); // remove $display_id
}
$view = views_get_view($name);
if (is_object($view)) {
if (is_array($args)) {
$view->set_arguments($args);
}
if (is_string($display_id)) {
$view->set_display($display_id);
}
else {
$view->init_display();
}
$view->pre_execute();
$view->execute();
$view->render();
//dd($view->style_plugin);
return $view->style_plugin->rendered_fields;
} else {
return array();
}
}
Then add the following code to your template:
<?php
$cars = views_get_rendered_fields('view name', 'default', [...any arguments to be passed to the view]);
foreach ($cars as $car): ?>
<div>Put your mockup in here. It might be helpful to run <?php die('<pre>'.print_r($car, 1).'</pre>'); ?> to see what the $car array looks like.</div>
<?php endforeach;
?>
Just change the placeholders in the code to whatever you want the markup to be, and you should be set!
As I mentioned above, it's always helpful to do <?php die('<pre>'.print_r($car,1).'</pre>'); ?> to have a visual representation of what the array looks like printed.
I use views_get_rendered_fields all the time in my code because it allows me to completely customize the output of the view.
As a Reminder: Always clear your caches every time you create a new template.
Best of luck!