I need to update values in all posts of a wordpress installation on a regular base. I was gooing to use shortcodes to insert the request into the wordpress post. Then use a custom functions.php that holds all the variables that need to be updated from time to time.
I got it working. Somehow but not the way I intended to use it. I'm a total beginner. Please consider this when answering my questions.
I want to have a function that reads what comes after honda_ and displays the correct value in wordpress without having to create a separate shortcode for each variable.
When entering [honda_link] wordpress should display the value from honda_link. When entering [honda_longlink] the value from honda_longlink variable should get displayed. I don't want to create a shortcode for each value.
I came up with this as a working solution...
// Honda
function honda() {
$honda_link = 'www.honda.com';
$honda_longlink = 'http://www.honda.com';
$honda_free = 'Free';
$honda_new = '23.688 $';
$honda_mileage = '00';
return $honda_link;
}
add_shortcode('neu', 'honda_link');
I tried some approaches by using an array but it ultimately failed all the time. I also tried it with if statements but wasn't able to get the right value displayed.
Someone willing to help a noob? I think I need to see a working example in order to understand it. The code snippets I have been looking at (that do something similiar but not the same I want to achieve) did confuse me more than they helped me.
I came up with this / Which works in a way but... This isn't very comfortable to use.
add_shortcode('HONDA','HONDA_TEST');
function HONDA_TEST($atts = array(), $content = null, $tag){
shortcode_atts(array(
'var1' => 'default var1',
'var2' => false,
'var3' => false,
'var4' => false
), $atts);
if ($atts['var2'])
return 'honda2';
else if ($atts['var3'])
return 'honda3';
else if ($atts['var4'])
return 'honda4';
else
return 'honda1';
}
So now when using:
[HONDA var1="novalue"][/HONDA]
[HONDA var2="novalue"][/HONDA]
[HONDA var3="novalue"][/HONDA]
[HONDA var4="novalue"][/HONDA]
it shows:
honda1
honda2
honda3
honda4
and so on.
Is there a better way to achieve the intended goal from post #1 ? Any way I could import the $variables from 1st post in bulk for example?
I don't have a working WP setup right now to test, but could you try this:
add_shortcode('HONDA','HONDA_TEST');
function HONDA_TEST($atts = array(), $content = null, $tag){
$atts = shortcode_atts(array(
'model' => 1,
), $atts);
$myHondas = [1 => 'honda1', 'honda2', 'honda3'];
return isset($myHondas[$atts['model']]) ? $myHondas[$atts['model']] : 'unknown model id';
}
And use it with [HONDA model="1"], [HONDA model="2"]
I am a coding beginner and have my PHP/HTML web project in German. Now I want to make it available in English in the easiest way. I don't want to add other languages in the future, so I want to try it in the easiest (and maybe not the most proper) way.
I have PHP files with HTML content and the selected language available in a var, i.e.:
<?php
$lang = "en";
?>
<h1>Title in German</h1>
So all the German words are inline HTML. My idea was to create something like:
<h1>[de]Title in German[/de][en]Title in English[/en]</h1>
But I have no idea how to replace it on every load in a smart way. So it is more a topic on "live replacement".
Working with constants in an external language file is of course also an option, like all the other options to make a multilingual site I found on Stackoverflow.
But maybe there is a "quick and dirty" possibility option like the one I mentioned?
Thank you for every hint!
You could try and do this will almost only HTML and CSS. You would need to add this at the top of your page:
<?php
$pageLanguage = "en";
function getLanguageStyle($showLanguage)
{
global $pageLanguage;
$display = ($showLanguage == $pageLanguage ? 'inline' : 'none');
return " span.$showLanguage { display: $display }\n";
}
echo "<style>\n".
getLanguageStyle('en').
getLanguageStyle('de').
"</style>\n";
?>
It sets up a style for each language, which you can then use like this:
<h1><span class="de">Title in German</span><span class="en">Title in English</span></h1>
The advantage here is that you don't need to mix HTML and PHP. This is not a normal way of doing this, but it will work. On very complex pages, where these styles are applied after the first render, this might not be pleasant for your visitors.
Usually translations are made that way:
You have key to translation map for each language, then you request some function that takes proper map for that language and returns translation:
function translate(string $lang, string $key) {
/*
* This usually sits in some file in dir like `/src/i18n/en.json`
* And you do then `$translations = json_decode(require "/src/i18n/{$lang}.json")`
*/
$translations = [
'en' => [
'page.title' => 'Page Title',
...
],
'de' => [
'page.title' => 'Page Title In German',
...
],
];
return $translations[$lang][$key] ?? $key;
}
<h1><?= translate($lang, 'page.title'); ?></h1>
I use a php-script within a plugin on a Wordpress-site to geocode an user-supplied address. After this I would like to visualize the point on a leaflet map. In order to do so I wanted to use the built-in functions from the leaflet-map plugin. I tracked down the class for this in the class.map-shortcode.php-file: Leaflet_Map_Shortcode. This class provideds the function shortcode. This is also added to the shortcode in Wordpress (Lines 135 onwards):
'leaflet-map' => array(
'file' => 'class.map-shortcode.php',
'class' => 'Leaflet_Map_Shortcode');
foreach ($this->_shortcodes as $shortcode => $details) {
include_once $shortcode_dir . $details['file'];
add_shortcode($shortcode, array($details['class'], 'shortcode'));
My Intention was using this in a straightforward way:
<?php
... some code for geocoding...
$coords = array("lng" => 11, "lat" =>43 );
$myMap= new Leaflet_Map_Shortcode;
$myMap->shortcode($coords);
?>
But nothing happens (i.e. nothing is displayed). So this leads me to several questions:
Why does this not work?
What's the best way of debugging this code?
Is there a better solution to my problem?
Turns out it is very easy due to a hint in the comments:
$mapPrint = $myMap->shortcode($coords);
echo($mapPrint);
I am attempting to refactor my app using the MVC paradigm.
My site displays charts. The URLs are of the form
app.com/category1/chart1
app.com/category1/chart2
app.com/category2/chart1
app.com/category2/chart2
I am using Apache Rewrite to route all requests to index.php, and so am doing my URL parsing in PHP.
I am working on the enduring task of adding an active class to my navigation links when a certain page is selected. Specifically, I have both category-level navigation, and chart-level sub-navigation. My question is, what is the best way to do this while staying in the spirit of MVC?
Before my refactoring, since the nav was getting relatively complicated, I decided to put it into an array:
$nav = array(
'25th_monitoring' => array(
'title' => '25th Monitoring',
'charts' => array(
'month_over_month' => array(
'default' => 'month_over_month?who=total&deal=loan&prev='.date('MY', strtotime('-1 month')).'&cur='.date('MY'),
'title' => 'Month over Month'),
'cdu_tracker' => array(
'default' => 'cdu_tracker',
'title' => 'CDU Tracker')
)
),
'internet_connectivity' => array(
'title' => 'Internet Connectivity',
'default' => 'calc_end_to_end',
'charts' => array(
'calc_end_to_end' => array(
'default' => 'calc_end_to_end',
'title' => 'calc End to End'),
'quickcontent_requests' => array(
'default' => 'quickcontent_requests',
'title' => 'Quickcontent Requests')
)
)
);
Again, I need to know both the current category and current chart being accessed. My main nav was
<nav>
<ul>
<?php foreach ($nav as $category => $category_details): ?>
<li class='<?php echo ($current_category == $category) ? null : 'active'; ?>'>
<?php echo $category_details['title']; ?>
</li>
<?php endforeach; ?>
</ul>
</nav>
and the sub-nav was something similar, checking for current_chart instead of current_category.
Before, during parsing, I was exploding $_SERVER['REQUEST_URI'] by /, and breaking the pieces up into $current_category and $current_chart. I was doing this in index.php. Now, I feel this is not in the spirit of the font controller. From references like Symfony 2's docs, it seems like each route should have its own controller. But then, I find myself having to define the current category & chart multiple times, either within the template files themselves (which doesn't seem to be in the spirit of MVC), or in an arbitrary function in the model (which would then have to be called by multiple controllers, which is seemingly redundant).
What is the best practice here?
Update: Here's what my front controller looks like:
// index.php
<?php
// Load libraries
require_once 'model.php';
require_once 'controllers.php';
// Route the request
$uri = str_replace('?'.$_SERVER['QUERY_STRING'], '', $_SERVER['REQUEST_URI']);
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && (!empty($_GET)) && $_GET['action'] == 'get_data') {
$function = $_GET['chart'] . "_data";
$dataJSON = call_user_func($function);
header('Content-type: application/json');
echo $dataJSON;
} elseif ( $uri == '/' ) {
index_action();
} elseif ( $uri == '/25th_monitoring/month_over_month' ) {
month_over_month_action();
} elseif ( $uri == '/25th_monitoring/cdu_tracker' ) {
cdu_tracker_action();
} elseif ( $uri == '/internet_connectivity/intexcalc_end_to_end' ) {
intexcalc_end_to_end_action();
} elseif ( $uri == '/internet_connectivity/quickcontent_requests' ) {
quickcontent_requests_action();
} else {
header('Status: 404 Not Found');
echo '<html><body><h1>Page Not Found</h1></body></html>';
}
?>
It seems like when month_over_month_action() is called, for instance, since the controller knows the current_chart is month_over_month, it should just pass that along. This is where I'm getting tripped up.
There are not "best practices" in this area. Though, there are some, that are more often used then others, and some, that are extremely bad ideas (unfortunately, these two groups tend to overlap).
Routing in MVC
While technically not a part of MVC design pattern, when applied to Web, your application needs to know which controller to initialize and what method(s) to call on it.
Doing explode() to gather this sort of information is a bad idea. It is both hard to debug and maintain. A much better solution is to use regular expressions.
Basically you end up having a list of routes, that contain a regular expression and some fallback values. You loop through that list and on fists match extract the data and apply default values, where data was missing.
This approach also frees you to have much wider possibilities for order of parameters.
To make the solution easier to use, you can also add functionality, that turns a notation string into a regular expression.
For example (taken from some unit-test, that I have):
notation: test[/:id]
expression: #^/test(:?/(?P<id>[^/\.,;?\n]+))?$#
notation: [[/:minor]/:major]
expression: #^(:?(:?/(?P<minor>[^/\.,;?\n]+))?/(?P<major>[^/\.,;?\n]+))?$#
notation: user/:id/:nickname
expression: #^/user/(?P<id>[^/\.,;?\n]+)/(?P<nickname>[^/\.,;?\n]+)$#
While creating such a generator will not be all that easy, it would be quite reusable. IMHO the time invested in making it would be well spent. Also, the use of (?P<key>expression) construct in regular expressions provides you with a very useful array of key-value pairs from the matched route.
Menus and MVC
The decision about which menu item to highlight as active should always be the responsibility of current view instance.
More complicated issue is where the information, that is necessary for making such decision, comes from. There are two source if data that are available to a view instance: information that was passed to view by controller and data, that view requested from model layer.
The controller in MVC takes the user's input and, based on this input, it changes the state of current view and model layer, by passing said values. Controller should not be extracting information from model layer.
IMHO, the better approach in this case is to relay on model layer for information about both menu content and the currently active element in it. While it's possible to both hardcode the currently active element in view and relay on controllers passed informations, MVC is usually used in large scale application, where such practices would end up hurting you.
The view in MVC design pattern is not a dumb template. It's a structure, that is responsible for UI logic. In context of Web that would mean creating a response from multiple template, when necessary, or sometimes just simply sending an HTTP location header.
Well, I had almost the same trouble when was writing CMS-like product.
So I've spend some time trying to figure out how to make this work and keep the code more maintainable and clean as well.
Both CakePHP and Symfony route-mecanisms have a bit inspired me but it wasn't good enough for me.
So I'll try to give you an example of how I do this now.
My question is, what is the best way to do this while staying in the
spirit of MVC?
First, In general, best practice is NOT TO USE procedural approach with MVC in web development at all.
Second, keep the SRP.
From references like Symfony 2's docs, it seems like each route should
have its own controller.
Yeah, that's right approach, but it doesn't mean that another route match can't have the same controller, but different action.
The main disadvantage of your approach (code that you have posted) is that you mix responsibilities and you're not implementing MVC-inspired pattern.
Anyway, MVC in PHP with procedural approach is just a horrible thing.
So, what exactly you are mixing is:
Route mechanism logic (It should be another class) not in a "controller" and route map as well
Request and Response responsibilites (I see that it isn't obvious to you)
Class autoloading
Controller logic
All those "parts" should have one class. Basically, they have to be included in index or bootstrap files.
Also, by doing so:
require_once 'controllers.php';
You automatically include ALL controllers per match (even on no-match). It actually has nothing to do with MVC and leads to memory leaks.
Instead, you should ONLY include and instantiate the controller that matches against URI string.
Also, be careful with include() and require() as they may lead to code duplication if you include the same file somewhere twice.
And also,
} elseif ( $uri == '/' ) {
index_action();
} elseif ( $uri == '/25th_monitoring/month_over_month' ) {
month_over_month_action();
} elseif ( $uri == '/25th_monitoring/cdu_tracker' ) {
cdu_tracker_action();
} elseif ( $uri == '/internet_connectivity/intexcalc_end_to_end' ) {
intexcalc_end_to_end_action();
It's extremely unwise to do a match using if/else/elseif control structures.
Okay, what if you have 50 matches? or even 100? Then you need to write 50 or 100 times to write else/elseif accordingly.
Instead, you should have a map and (an array for example) iterate over it on each HTTP request.
The general approach of using MVC with routing mechanism comes down to:
Matching the request against route map (and keep somewhere parameters if we have them)
Then instantiate appropriate controller
Then pass parameters if we have them
In PHP, the implementation would look like:
File: index.php
<?php
//.....
// -> Load classes here via SPL autoloader or smth like this
// .......
// Then -> define or (better include route map from config dir)
$routes = array(
// -> This should default one
'/' => array('controller' => 'Path_To_home_Controller', 'action' => 'indexAction'),
'/user/:id' => array('controller' => 'Path_to_user_controller', 'action' => 'ViewAction'),
// -> Define the same controller
'/user/:id/edit' => array('controller' => 'Path_to_user_controller', 'action' => 'editAction'),
// -> This match we are going to hanlde in example below:
'/article/:id/:user' => array('controller' => 'SomeArticleController', 'action' => )
);
// -> Also, note you can differently handle this: array('controller' => 'SomeArticleController', 'action' => )
// -> Generally controller key should point to the path of a matched controller, and action should be a method of the controller instance
// -> But if you're still on your own, you can define it the way you want.
// -> Then instantiate common classes
$request = new Request();
$response = new Response();
$router = new Router();
$router->setMap( $routes );
// -> getURI() should return $_SERVER['REQUEST_URI']
$router->setURI( $request->getURI() );
if ( $router->match() !== FALSE ) {
// -> So, let's assume that URI was: '/article/1/foo'
$info = $router->getAll();
print_r ( $info );
/**
* Array( 'parameters' => Array(':id' => '1', ':user' => 'foo'))
* 'controller' => 'Path_To_Controller.php'
* 'action' => 'indexAction'
*/
// -> The next things we are going to do are:
// -> 1. Instantiate the controller
// -> 2. Pass those parameters we got to the indexAction method
$controller = $info['controller'];
// -> Assume that the name of the controller is User_Controller
require ( $controller );
// -> The name of class should also be dynamic, not like this, thats just an example
$controller = new User_Controller();
$arguments = array_values( $info['parameters'] );
call_user_func_array( array($controller, $info['action']), $arguments );
// -> i.e we just called $controller->indexAction('1', 'foo') "dynamically" according to the matched URI string
// -> idealy this should be done like: $response->send( $content ), however
} else {
// -> In order not to show any error
// -> redirect back to "default" controller
$request->redirect('/');
}
In my MVC-inspired applications I do route like this:
(Where I use Dependecy Injection and keep the SRP)
<?php
require (__DIR__ . '/core/System/Auload/Autoloader.php');
Autoloader::boot(); // one method includes all required classes
$map = require(__DIR__ . '/core/System/Route/map.php');
$request = new Request();
$response = new Response();
$mvc = new MVC();
$mvc->setMap( array_values($map) );
// -> array_values($map) isn't accurate here, it'd be a map of controllers
// -> take this as a quick example
$router = new Router();
$router->setMap( $map );
$router->setURI( $request()->getURI() );
if ( $router->match() !== FALSE ) {
// -> Internally, it would automatically find both model and view instances
// -> then do instantiate and invoke appropriate action
$router->run( $mvc );
} else {
// No matches handle here
$request->redirect('/');
}
I found this to be more appropriate for me, after poking around Cake and Symfony.
One thing I want to note:
It's not that easy to find good articles about MVC in PHP. Most of them are just wrong.
(I know how it feels, because first time I've started to learn from them, like so many people do)
So my point here is:
Don't make the same mistake like I did before. If you want to learn MVC, start doing this by reading
Zend Framework or Symfony Tutorials. Even the ones are bit different, the idea behing the scene is the same.
Back to the another part of the question
Again, I need to know both the current category and current chart
being accessed. My main nav was
<nav>
<ul>
<?php foreach($nav as $category => $category_details): ?>
<li class='<?php echo ($current_category == $category) ? null : 'active'; ?>'>
<?php echo $category_details['title']; ?>
</li>
<?php endforeach; ?>
</ul>
</nav>
First of all, don't concatenate the string, instead use printf() like:
<?php echo $category_details['title']; ?>
If you need this to be everywhere (or at least in many different templates), I'd suggest to this to have in a common abstact View class.
For example,
abstract class View
{
// -> bunch of view reusable methods here...
// -> Including this one
final protected function getCategories()
{
return array(
//....
);
}
}
class Customers_View extends View
{
public function render()
{
$categories =& $this->getCategories();
// -> include HTML template and then interate over $categories
}
}
I want to display some text in a CDetailView which was previously encoded in MarkDown format.
this is my view code:
<?php
$this->widget('zii.widgets.CDetailView', array(
'data'=>$model,
'attributes'=>array(
'title',
array(
'name'=>'text',
'type'=>'raw',
'value'=>$this->markdown->transform($model->text)
),
'author_id',
'date_added',
),
));
?>
and in my controller, I instantiate a CMarkDown filter like this:
private $_markdown = null;
public function getMarkdown()
{
if ( $this->_markdown === null)
{
$this->_markdown = new CMarkdown();
$this->_markdown->purifyOutput = true;
}
return $this->_markdown;
}
notice how I explicitly set purifyOutput to true.
So I created a mock post full of things like marquee and injected javascript to see how it would behave and it didn't filter anything at all!! I got an alert on my face and the marquee was all happy moving around on the page....
I found a workaround which was to set 'type'=>'html' in the CDetailView but I shouldn't need to do that, should I??
Isn't that purifyOutput option supposed to filter unwanted stuff out for me when I call the ->transform() method??
Some help, please.
To purify the output you need to use CMarkdown::processOutput, not the transform method (that one is more low-level and does not honor purifyOutput).
If you look at the documentation carefully, you will notice that processOutput mentions the purifyOutput setting while transform does not. Viewing the source confirms this.