How to create wordpress function? - php

i need to create function in word press function file to print some HTML cord. i tried this function.
function pre($chord){
echo '<pre>$chord</pre>'
}
and i use it in my post like this
<?php pre("sd");?>
and it will not work. please help me.

You are building your string incorrectly. when mixing html and php strings you need to concatenate the data like so...
function pre( $chord ) {
echo '<pre>' . $chord . '</pre>';
}
Also bear in mind that Wordpress is a large and modular CMS so by naming your function something as simple as pre you run the risk of conflicting with some other function called pre. It's good practise to prefix your functions with a unique string of letters like so...
function abc_pre( $chord ) {
echo '<pre>' . $chord . '</pre>';
}
Use whatever works for you.
Dan

Related

get all categories listing from database

Main purpose is to get all categories listing from database by passing variables to url and show it to the main page.here i have omitted some code bt i tried to clarify.
1.can I exclude encodeHtml() method, too difficult for me to understand
2.i am not getting specially this part of code and having my head for 4 days
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";//here id is 'category id' from database. this full line will echo what?
echo Helper::getActive(array('category' => $cat['id']));//it will output what ?
echo ">";
echo Helper::encodeHtml($cat['name']);//as from ur answer can we omit encodeHTML() method and use htmlspecialchars($cat['name']); instead ?
echo "</a>
3.any easier solution will be more appreciated
in our database we have 'id' and 'name' of catagory listing
please check below for reference
/*below is the code in header section of template */
<?php
$objCatalogue = new Catalogue();// creating object of Catalogue class
$cats = $objCatalogue->getCategories(); // this gets all categories from database
<h2>Categories</h2>
<?php
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";
echo Helper::getActive(array('category' => $cat['id']));
echo ">";
echo Helper::encodeHtml($cat['name']);
echo "</a></li>";
}
?>
/*below is the helper class which is Helper.php */
public static function getActive($page = null) {
if(!empty($page)) {
if(is_array($page)) {
$error = array();
foreach($page as $key => $value) {
if(Url::getParam($key) != $value) //getParam takes name of the parameter and returns us the value by $_GET
{
array_push($error, $key);
}
}
return empty($error) ? " class=\"act\"" : null;
}
}
//CHECK THIS LINE BROTHER
return $page == Url::currentPage() ? " class=\"act\"" : null;// url::currentPage returns the current page but what is 'class =act ' :(
}
public static function encodeHTML($string, $case = 2) {
switch($case) {
case 1:
return htmlentities($string, ENT_NOQUOTES, 'UTF-8', false);
break;
case 2:
$pattern = '<([a-zA-Z0-9\.\, "\'_\/\-\+~=;:\(\)?&#%![\]#]+)>';
// put text only, devided with html tags into array
$textMatches = preg_split('/' . $pattern . '/', $string);
// array for sanitised output
$textSanitised = array();
foreach($textMatches as $key => $value) {
$textSanitised[$key] = htmlentities(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
}
foreach($textMatches as $key => $value) {
$string = str_replace($value, $textSanitised[$key], $string);
}
return $string;
break;
}
}
Firstly, in your URL (/?page=catalogue&category=) you don't need to put &, as this is an HTML entity for actually displaying an ampersand in a web page. Just use /?page=catalogue&category=.
Secondly, you can use urlencode() to prepare strings for sending in the URL, and urldecode() on the other end.
In answer to your first point you just need to make sure that ANYTHING from the user (whether via $_POST or $_GET) is sanitized, prior to being used in code, output to a web page, or used in database queries. Use htmlspecialchars() for cleaning before outputting to a web page, and prepared statements prior to entering user input into a query.
In answer to your second point please read the documentation in the links I have provided above. Just reading the documentation on htmlspecialchars() will help you a lot.
Hope this helps.
Alright then.
<?php
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";
echo Helper::getActive(array('category' => $cat['id']));
echo ">";
echo Helper::encodeHtml($cat['name']);
echo "</a></li>";
}
?>
Im just going to kindof skim through it, because honestly if you really want to learn all this you should probably google the shit out of every piece of code you don't understand, it's the way we all learn things.
< ?php announces some php script to follow. And as you can see, there does follow some php code after.
foreach is a way of getting each element from an array or list and doing something to that element.
echo sends whatever string comes after it to the page, or whatever is listening to its output. In this case, it looks like the echo's are printing some <li> list item with an <a> anchor in it.
Helper::getActive(): Helper is some class that is defined somewhere, :: is syntax for calling a static function that belongs to the class (Helper in this case). getActive is the function name.
array('category' => $cat['id'] is a piece of code that creates an array with 1 element in it, being one with key 'category' and a value of whatever is in $cat['id'].
By looking at getActive: it looks like it's a function that checks the url for some value so it can determine which page to display. It also checks if the url contains errors.
By lookingat encodeHtml(): it looks like it's a function that makes sure that whatever text you're trying to put on the screen, isn't something that could cause harm. In some situations, people will try to make your server print javascript that could harm the user (by sending personal data to somewhere). The encodeHtml() will ensure that no such thing can be done by stripping certain characters from the text you're about to send to the page.
USE GOOGLE.

In PHP, can you DEFINE a constant that can be used in function names?

In Drupal, there are many functions that are hook_functionname1, hook_functionname2. When writing a module, you have to replace the text 'hook' with your module name, so Drupal loads your module "my_drupal_module" and runs hooks like "my_drupal_module_functionname1" and "my_drupal_module_functionname2".
Is it possible in PHP to use DEFINE to simply define the word "hook" and set it to a string? If it is possible, then you should be able to copy and paste word-for-word hook_anything and not have to change it. And, if you ever wanted to change the name of your module, you would merely change the single constant, rather than find/replace all the function names.
So can you use DEFINE or some other setting to meta-program in PHP?
You want something like:
$moduleFunctionName = 'hook';
$functionNameOne = $moduleFunctionName . '_functionname1';
$functionNameTwo = $moduleFunctionName . '_functionname2';
$functionNameOne = function($var) {
// blah
}
..//
Function $functionNameOne is defined through anonymous function. It becames available in php from php 5.3.0
Maybe you want something like this
<?
define('PREFIX', 'myprefix');
//like this time you deside that this will me the second part
$somevar = '_this_function_name';
// now we combine prefix and name
$function_name = PREFIX . $somevar;
// now we check if we can run this function
if(!function_exists($function_name)){
echo "no function $funcion_name exist";
}
else{
$function_name();
}
function myprefix_this_function_name(){
echo 'running function';
}
?>
this will output
running function
This actually works:
define('FN_NAMESPACE', 'hook_');
${FN_NAMESPACE . 'functionNameOne'} = function($var) {
echo "Hi, I got $var\n";
};
$hook_functionNameOne('test');
Will output
Hi, I got test

How to echo an function

I've been struggling to echo the output of a function. I tried this:
echo 'myFunction('foo')';
.. which obviously won't work, due to the extra single quotes. Any suggestions?
Let's take this function :
function getStr()
{
return "hello";
}
It will simply return a string, which means, calling this :
echo getStr();
Has the same exact result as calling this :
echo "hello";
Which means, the result of your function can be treated just like a variable (except you cant modify it), so you can do whatever you want with the result :
$string = getStr() . ' - ' . getStr();
echo $string; // Will print "hello - hello";
After trying a little while, I tried calling echo as an function:
echo (myFunction('foo'));
This works perfectly. I couldn't find this elsewhere on the internet (maybe I'm just a bad googler). Anyways, I thought I could might share this with you guys. In case anyone ever runs into the same problem.
Try this:
echo myFunction('foo');

Closure within a string in PHP

I want to create and execute a closure within a string in PHP and it's not liking the way that I do it.
This code doesn't work...
echo ( 'Hello, ' . (function($s) { return $s; })('World!') );
Yet, this is completely valid and works as intended...
$f = (function($s) { return $s; });
echo ( 'Hello, ' . $f('World!') );
Why won't the first one work and is there a way to do it in one line (not because I think it's efficient, because I'm sure it's not)?
You may want to take a look at Self Executing functions in PHP5.3?.
Essentially, no self-invoking with "(...)()" until (maybe) sometime in 5.4.
https://wiki.php.net/rfc/fcallfcall
I believe that's only possible in PHP 5.4: http://php.net/manual/en/migration54.new-features.php

echo function output inside html

I have something like this in one field of my table(MySql):
$data = '<td>apple</td>';
echo $data;
I select this field and echo it into the page.I want to replace 'apple' word with a php function that return a word.So I thought
$data = '<td>myphp_function('fruit');</td>';
echo $data;
but what I see in the page is exactly the line above and not my function output.
how can I do it?
I am not sure if i could explain my mean clearly...
Edited.
According to your last edit, what you need is the following:
$data = '<td>' . myphp_function('fruit') . '</td>';
echo $data;
This is assuming your myphp_function() will return some kind of value.
If the function echoes the value, it will not work as expected!
You can only execute PHP when you open PHP tags. Other than that, it's just plain text/html.
<td>myphp_function('fruit');</td>
To execute your function you have to open PHP tags:
<td><?php myphp_function('fruit'); ?></td>
you have to insert some sort of placeholder into your text. Like this
<td>[fruit]</td>
and then do a replace before printing it out:
$fruit = 'apple';
$text = str_replace('[fruit]',$fruit,$text);
Of course, for the real life usage there will be more complex solution.
So, you will do yourself enormous favor, if you post here your real task with real data example, not oversimplified and useless abstract question.

Categories