Wordpress do_shortcode strange behavior - php

I am developing a WP plugin which processes shortcodes and displays amazon item data in place of them. The plugin is working as desired, except for a little strange behavior. You can see my test run at http://passivetest.themebandit.com/test-post-for-zon-plugin/ .
If you scroll down on that page, you can see that 4 "1" s are appended to the content. The shortcode is processed 4 times in this page, and each time WP is adding an undesired 1 to the output. I don't understand why this is happening. There is no "1" anywhere in my html files, and its nowhere in the post content. All my functions just return the content that is to be replaced in place of the shortcode. Can someone please give an explanation for it and let me know how to remove these? Thanks in advance..
My code is as follows:
add_shortcode('zon_product', 'zon_process_shortcode');
// Zon Shortcode processor
function zon_process_shortcode($attributes, $content = null) {
global $zon_html_path;
// default options for shortcode
$options = array('asin' => '', 'style' => 'compact', 'loc' => 'com');
extract(shortcode_atts($options, $attributes));
$asin = $attributes['asin'];
// first find asin in local zon_data table
$zdb = ZonDbHandler::instance();
$product = $zdb->findASIN($asin);
if ($product) {
// if product exists in db, render template
return zon_display_product($product, $attributes);
} else {
// product does not exist in database, get data through amazon api worflow
$product = ZonLibrary::getAmazonProduct($asin, $attributes['loc']);
if ($product) {
// product data has been successfully retrieved and saved, render template
return zon_display_product($product, $attributes);
} else {
// error in fetching product data, check amazon access key id and api secret
$content = include($zon_html_path . 'html' . DIRECTORY_SEPARATOR . 'api_error.php');
return $content;
}
}
}
// Renders selected template with product data
function zon_display_product(ZonProduct $product, $attributes) {
global $zon_html_path;
global $zon_path;
// process other shortcode options
$view_vars = array();
$view_vars['style'] = (isset($attributes['style'])) ? $attributes['style'] : "default";
$view_vars['show_price'] = (isset($attributes['show_price']) && $attributes['show_price'] == 0) ? false : true;
$view_vars['price_updates'] = (isset($attributes['price_updates']) && $attributes['price_updates'] == 0) ? false : true;
$view_vars['hide_unavailable'] = (isset($attributes['hide_unavailable']) && $attributes['hide_unavailable'] == 1) ? true : false;
$view_vars['show_desc'] = (isset($attributes['show_desc']) && $attributes['show_desc'] == 0) ? false : true;
// check if template file exists
if (!is_file($zon_html_path . 'html' . DIRECTORY_SEPARATOR . $view_vars['style'] . '.php')) {
$content = 'ERROR! Zon Template not found. Please check you are using a correct value for the "style" parameter.';
return $content;
} else {
// get product array
$product = $product->getArray();
// if product is unavailable and hide_unavailable is true, return unavailable template
if ($view_vars['hide_unavailable']) {
if ((strpos($product['availability'], "Usually") === false) && strpos($product['availability'], "ships") === false) {
$content = include($zon_html_path . 'html' . DIRECTORY_SEPARATOR . 'unavailable.php');
return $content;
}
}
// render chosen template file
$content = include($zon_html_path . 'html' . DIRECTORY_SEPARATOR . $view_vars['style'] . '.php');
return $content;
}
}

Related

Removing document root from file path Zend Framework 2

I'm trying to display an image but I am running into the error of Not allowed to load local resource: file:///C:/xampp/htdocs/public/images/profile/jimmy/status/boned.jpg in the browser console. What I am trying to do is use the base path provided by Zend Framework 2 but I'm retrieving the images in the model so (as far as I know), I can't use $this->basePath() like I would in the view.
This is my json string I am returning but would like to just be able to return /images/profile/jimmy/status/boned.jpg and whatever other images are in there.
I'm getting all the files outside of the directory 'status'. I am trying to get the files inside the status directory. When I did a var_dump this is what I get string(43) "C:\xampp\htdocs/public/images/profile/jimmy" I'm unclear why it is omitting the status directory after '/jimmy'
json string being returned:
{"feed":{"username":"Timmy","status":["this is jimmy, test"],"images":["videos","status","sithtoon.jpg","sith.jpg","edited_photos","diploma.jpg","current","albums","Screenshot_2016-08-09_21_28_13_361272.jpg","Screenshot_2016-08-05_17_55_48_500802.jpg","515gIIJ-Imgur.png",".htaccess"]}}
Here is the relevant PHP code (in the model):
public function listFriendsStatus()
{
$user_id = $this->getUserId()['id'];
// get the friend ids based on user id
// and then compare the friend id to the id in status table
$friend_query = new Select('friends');
$friend_query->columns(array('friend_id'))
->where(array('user_id' => $user_id));
$query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($friend_query),
Adapter::QUERY_MODE_EXECUTE
);
if ($query->count() > 0) {
$friend_id = array();
foreach ($query as $result) {
$friend_id[] = $result['friend_id'];
}
$status = new Select('status');
$status->columns(array('status'))
->where(array('id' => $friend_id));
$status_query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($status),
Adapter::QUERY_MODE_EXECUTE
);
if ($status_query->count() > 0) {
// check if a image was used
$members = new Select('members');
$members->columns(array('username'))
->where(array('id' => $friend_id));
$image_query = $this->sql->getAdapter()->query(
$this->sql->buildSqlString($members),
Adapter::QUERY_MODE_EXECUTE
);
if ($image_query->count() > 0) {
foreach ($image_query as $value) {
if (is_dir(getcwd() . '/images/profile/' . $value['username'] . '/status/')) {
$status_dir = pathinfo(getcwd() . '/images/profile/' . $value['username'] . '/status/');
}
}
$images = array();
chdir($status_dir['dirname']);
var_dump($status_dir['dirname']);
// retrieve the image inside the status directory
foreach (array_diff(scandir($status_dir['dirname'], 1), array('.', '..')) as $values) {
$images[] = $values;
}
} else {
throw new FeedException("The user does not exist in the user table.");
}
$status = array();
// get all the statuses
foreach ($status_query as $rows) {
$status[] = $rows['status'];
}
return array('username' => ucfirst($value['username']), 'status' => $status, 'images' => $images); // how to just get the basePath path with zf2
} else {
throw new FeedException("No status was found for your friends.");
}
} else {
throw new FeedException(sprintf("Could not locate any friends for %s", $this->user));
}
}
controller code:
public function getfriendstatusAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
try {
echo json_encode(array('feed' => $this->getStatusService()->listFriendsStatus()));
} catch (FeedException $e) {
echo json_encode(array('fail' => $e->getMessage()));
}
return $view_model;
}
jquery code:
$.getJSON('/members/feed/get-friend-status', function(data) {
$.each(data, function(i, item) {
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin').find('h4').html(data[i].username);
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin').find('p').html(data[i].status);
$('.w3-container.w3-card-2.w3-white.w3-round.w3-margin').find('img').attr('src', data[i].images);
});
}).fail(function(response) {
console.log(response);
});
I've been trying to use other directory functions provided with PHP but if I try anything, I run into the error directory could not be found. Basically what I am trying to do is use the similiar approach of $this->basePath() but in a model.
I hope that is clear enough..
Thanks!
Here is a screenshot of what I'm getting and how I want to get the status directory, not the directory outside of it.
I have an idea.
In your code is:
$status_dir = pathinfo(getcwd() . '/images/profile/' . $value['username'] . '/status/');
// ..............
chdir($status_dir['dirname']);
var_dump($status_dir['dirname']);
Try:
var_dump($status_dir);
I guess 'status' will be in 'basename' and / or in 'filename'
pathinfo gets last segment of argument string path as 'basename'.
Pathinfo only parses string as path and return array info, don't check it for isDir or isFile. Your correct chdir should looks like chdir($status_dir['dirname'] . '/' . $status_dir['basename'] ); if you need use of pathinfo.
In other words: dirname of 'images/profile/jimmy/status' is 'images/profile/jimmy' and its a reason why you don't see status in var_dump($status_dir['dirname']) and why chdir($status_dir['dirname']) not working correctly.

How do I change PHP Scripts from MediaWiki to Wordpress Plugin?

I am working on a project where I have MediaWiki PHP Scripts that import publications information from a DB into a Publications Page.
I need to convert this scripts to Wordpress Plugin but I don't really know the best way to do it. Quite lost right now I try to do the Tutorial: Writing a simple WordPress plugin from scratch but I did not have success on that and I still don't have this working.
Original MediaWiki Code
Here you will see my original MediaWiki Code:
<?php
# the function registered by the extension gets the text between the
# tags as input and can transform it into arbitrary HTML code.
# Note: The output is not interpreted as WikiText but directly
# included in the HTML output. So Wiki markup is not supported.
# To activate the extension, include it from your LocalSettings.php
# with: include("extensions/YourExtensionName.php");
$wgExtensionFunctions[] = "wfExampleExtension";
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//
// Register the extension with the WikiText parser.
// The first parameter is the name of the new tag. In this case it defines
// the tag:
// <server-id> ... </server-id>
// The second parameter is the callback function for processing the text
// between the tags.
//
function wfExampleExtension() {
global $wgParser; // MediaWiki global variable
$wgParser->setHook("server-id", "renderSERVERID");
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//
// The callback function for converting the input text to HTML output.
// The function registered by the extension gets the text between the
// tags as $input and transforms it into arbitrary HTML code.
// Note: the output is not interpreted as WikiText but directly included in
// the HTML output. So Wiki markup is not supported.
//
// To activate the extension, include it from your LocalSettings.php
// with: include("extensions/YourExtensionName.php");
//
// $argv is an array containing any arguments passed to the extension like:
// <server-id what="foo" bar>..
//
// According to the metawiki, this works in MediaWiki 1.5.5.
// <server-id what="person" id="62">This text is not actually used</server-id>
//
// Personal information:
// <server-id what='person' id='62'></server-id>
//
// Information for a group:
// <server-id what='publications' cc='IP02'></server-id>
//
function renderSERVERID($input, $argv) {
// connect to the database
$idDBLink = odbc_connect('SERVER ID', 'some_db', 'some_db_pw');
if (!$idDBLink) { exit("Connection to database failed! Please contact root#server-id.org."); }
$html = "";
if ($argv['what'] == 'person') {
$id = split(",", trim($argv["id"]));
if ($id != '') {
// information about someone:
// 1. personal contacts and summary
// 2. publications by person
// 3. advisory work by person
//
$html .= personById($idDBLink, $id[0]);
$internalIds = authorIdByNumber($idDBLink, $id); // use all Ids
$html .= pubsById($idDBLink, $internalIds);
$html .= advisingById($idDBLink, $internalIds);
}
}
else if ($argv['what'] == 'advising') {
$id = split(",", trim($argv["id"]));
if ($id != '') {
$internalIds = authorIdByNumber($idDBLink, $id); // use all Ids
$html .= iconv('latin1', 'UTF-8', advisingById($idDBLink, $internalIds));
}
}
else if ($argv['what'] == 'publications') {
// information about some "centro de custo":
// 1. currently, only a list of publications
//
$cc = trim($argv["cc"]);
$id = trim($argv["id"]);
if ($cc != '') {
$html .= iconv('latin1', 'UTF-8', pubsByCC($idDBLink, $cc));
}
else if ($id != '') {
$html .= iconv('latin1', 'UTF-8', pubsById($idDBLink, authorIdByNumber($idDBLink, array($id))));
}
}
/*else if ($argv['what'] == 'publications') {
// information about some "centro de custo":
// 1. currently, only a list of publications
//
$cc = trim($argv["cc"]);
if ($cc != '') {
$html .= pubsByCC($idDBLink, $cc);
}
}*/
else if ($argv['what'] == 'calls') {
// information about some "centro de custo":
// 1. currently, only a list of publications
//
$cc = trim($argv["cc"]);
$showClosed = isset($argv['showclosed']) ? trim($argv['showclosed']) : "";
if ($cc != '') {
$html .= iconv('latin1', 'UTF-8', callsByCC($idDBLink, $cc, $showClosed == "yes"));
}
}
else {
// oops! no text...
}
odbc_close($idDBLink);
return $html;
}
?>
My WordPress Try Version
Here you will see what I try to do with WordPress Code:
<?php
// ==================================================
// WordPress Plugin
// ==================================================
/*
Plugin Name: Publications Importer
Plugin URI: http://someperson.me/downloads/publications-importer
Description: Integrates the Publications Importer plugin into your WordPress install.
Version: 0.0.1
Author: Someone
Author URI: http://someperson.me/
*/
require_once 'server-id-config.php';
require_once 'server-id-util.php';
require_once 'server-id-people.php';
require_once 'server-id-pubs.php';
require_once 'server-id-advising.php';
defined( 'ABSPATH' ) or die( 'Plugin file cannot be accessed directly.' );
if ( ! class_exists( 'Publication' ) ) {
class Publication
{
/**
* Tag identifier used by file includes and selector attributes.
* #var string
*/
protected $tag = 'publications-importer';
/**
* User friendly name used to identify the plugin.
* #var string
*/
protected $name = 'Publications Importer';
/**
* Current version of the plugin.
* #var string
*/
protected $version = '0.0.1';
public function __construct()
{
add_shortcode( $this->tag, array( &$this, 'shortcode' ) );
}
public function shortcode( $atts, $content = null )
{
extract( shortcode_atts( array(
'what' => false,
'cc' => false
), $atts ) );
$styles = array();
if ( is_numeric( $what ) ) {
$styles[] = esc_attr( 'what: ' . $what );
}
$classes = array(
$this->tag
);
if ( !empty( $cc ) ) {
$classes[] = esc_attr( $cc );
}
ob_start();
?><pre cc="<?php esc_attr_e( implode( ' ', $classes ) ); ?>"<?php
echo ( count( $styles ) > 0 ? ' style="' . implode( ' ', $styles ) . '"' : '' );
?>><p><?php echo $content; ?></p></pre><?php
return ob_get_clean();
}
}
new Publication;
}
// ==================================================
// END WordPress Plugin
// ==================================================
# the function registered by the extension gets the text between the
# tags as input and can transform it into arbitrary HTML code.
# Note: The output is not interpreted as WikiText but directly
# included in the HTML output. So Wiki markup is not supported.
# To activate the extension, include it from your LocalSettings.php
# with: include("extensions/YourExtensionName.php");
$wgExtensionFunctions[] = "wfExampleExtension";
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//
// Register the extension with the WikiText parser.
// The first parameter is the name of the new tag. In this case it defines
// the tag:
// <server-id> ... </server-id>
// The second parameter is the callback function for processing the text
// between the tags.
//
function wfExampleExtension() {
global $wgParser; // MediaWiki global variable
$wgParser->setHook("server-id", "renderSERVERID");
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//
// The callback function for converting the input text to HTML output.
// The function registered by the extension gets the text between the
// tags as $input and transforms it into arbitrary HTML code.
// Note: the output is not interpreted as WikiText but directly included in
// the HTML output. So Wiki markup is not supported.
//
// To activate the extension, include it from your LocalSettings.php
// with: include("extensions/YourExtensionName.php");
//
// $argv is an array containing any arguments passed to the extension like:
// <server-id what="foo" bar>..
//
// According to the metawiki, this works in MediaWiki 1.5.5.
// <server-id what="person" id="62">This text is not actually used</server-id>
//
// Personal information:
// <server-id what='person' id='62'></server-id>
//
// Information for a group:
// <server-id what='publications' cc='IP02'></server-id>
//
function renderSERVERID($input, $argv) {
// connect to the database
$idDBLink = odbc_connect('SERVER ID', 'some_db', 'some_db_pw');
if (!$idDBLink) { exit("Connection to database failed! Please contact root#server-id.org."); }
$html = "";
if ($argv['what'] == 'person') {
$id = split(",", trim($argv["id"]));
if ($id != '') {
// information about someone:
// 1. personal contacts and summary
// 2. publications by person
// 3. advisory work by person
//
$html .= personById($idDBLink, $id[0]);
$internalIds = authorIdByNumber($idDBLink, $id); // use all Ids
$html .= pubsById($idDBLink, $internalIds);
$html .= advisingById($idDBLink, $internalIds);
}
}
else if ($argv['what'] == 'advising') {
$id = split(",", trim($argv["id"]));
if ($id != '') {
$internalIds = authorIdByNumber($idDBLink, $id); // use all Ids
$html .= iconv('latin1', 'UTF-8', advisingById($idDBLink, $internalIds));
}
}
else if ($argv['what'] == 'publications') {
// information about some "centro de custo":
// 1. currently, only a list of publications
//
$cc = trim($argv["cc"]);
$id = trim($argv["id"]);
if ($cc != '') {
$html .= iconv('latin1', 'UTF-8', pubsByCC($idDBLink, $cc));
}
else if ($id != '') {
$html .= iconv('latin1', 'UTF-8', pubsById($idDBLink, authorIdByNumber($idDBLink, array($id))));
}
}
/*else if ($argv['what'] == 'publications') {
// information about some "centro de custo":
// 1. currently, only a list of publications
//
$cc = trim($argv["cc"]);
if ($cc != '') {
$html .= pubsByCC($idDBLink, $cc);
}
}*/
else if ($argv['what'] == 'calls') {
// information about some "centro de custo":
// 1. currently, only a list of publications
//
$cc = trim($argv["cc"]);
$showClosed = isset($argv['showclosed']) ? trim($argv['showclosed']) : "";
if ($cc != '') {
$html .= iconv('latin1', 'UTF-8', callsByCC($idDBLink, $cc, $showClosed == "yes"));
}
}
else {
// oops! no text...
}
odbc_close($idDBLink);
return $html;
}
?>
So what I exactly need to know is:
1) Should not WordPress be able to interpret the MediaWiki tags (for example: <server-id what='publications' cc='IP02'></server-id>) and do this automatically?
2) Where can I find more documentation about this kind of migrations?
3) Am I doing this the wrong way?
WordPress and MediaWiki are independent applications and one can not expect a plugin written for one to be directly portable to the other. If you are lucky some of the code may be reusable but it will not be as simple as a cut and paste. The two application has different ways of doing things.
1) No, WordPress will not be able to understand such tags. WordPress can be made to understand MediaWiki style markdown tags with additional plugins but I do not recognise the tag example you highlight.
2) I think your current approach is sound, you will need to understand what the MediaWiki code is doing and re-create this within a WordPress plugin. I doubt there is a short cut to this other than taking some time to get to grips with WP plugins. If you enjoy coding and writing plugins thin this is time well spent. Being able to customise WordPress is very useful.
3) Other than re-coding it yourself the other option would be to see if there is a WordPress plugin that does what you are looking for. Your question does not detail what exactly the functionality is that you are trying to add.
Having written plugins for both MediaWiki and WordPress I have found the easier more enjoyable to work with.

Custom Joomla 3 Button task not executing in my controller

I am trying to upload an external list of "groups" to add to my custom Joomla 3 component. I have created a CSV file and written a few functions that I hope will do it. I have created a custom button to start the task in my "groups" view.
When I push the button I get an SQL error that has absoloutle nothing to do with the functions so I have tried debugging and when the button is pressed its not even getting to my controller task before the sql error. I am so confused as to why.
This is the code I have
view.html.php TestViewGroups
JToolBarHelper::custom('group.uploadsave', '', '', 'Upload and Save', false);
TestControllerGroup
protected function uploadsave() {
$detail_headers = array(
'agm_date',
'preferred_media'
);
$rows = array_map('str_getcsv', file('groupdata.csv'));
$header = array_shift($rows);
foreach ($rows as $row) {
$entry = array_combine($header, $row);
foreach ($entry as $key => $value) {
if(in_array($key, $detail_headers)){
$details[$key]= $value;
unset($entry[$key]);
}
}
$entry['details'] = $details;
$this->saveUploaded($entry);
}
// Redirect to the list screen.
$this->setRedirect(
JRoute::_(
'index.php?option=' . $this->option . '&view=' . $this->view_list
. $this->getRedirectToListAppend(), false
)
);
}
protected function saveUploaded($dataIn = array()) {
$app = JFactory::getApplication();
$lang = JFactory::getLanguage();
$model = $this->getModel();
$table = $model->getTable();
$data = $dataIn;
$checkin = property_exists($table, 'checked_out');
// Determine the name of the primary key for the data.
if (empty($key))
{
$key = $table->getKeyName();
}
// To avoid data collisions the urlVar may be different from the primary key.
if (empty($urlVar))
{
$urlVar = $key;
}
$recordId = $this->input->getInt($urlVar);
// Populate the row id from the session.
$data[$key] = $recordId;
if (!$model->save($validData))
{
// Redirect back to the edit screen.
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError()));
$this->setMessage($this->getError(), 'error');
}
if ($checkin && $model->checkin($validData[$key]) === false)
{
// Save the data in the session.
$app->setUserState($context . '.data', $validData);
// Check-in failed, so go back to the record and display a notice.
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_CHECKIN_FAILED', $model->getError()));
$this->setMessage($this->getError(), 'error');
}
$this->setMessage(
JText::_(
($lang->hasKey($this->text_prefix . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS')
? $this->text_prefix
: 'JLIB_APPLICATION') . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS'
)
);
}
I am not using this as a regular function, its just a once off to upload the data initially.
The SQL error I am getting is like it is trying to load a list of groups?? not anything to do with the save function at all.
The saveUploaded is a similar function to the initial save function.
Thanks :-)
**** Edit *****
I have just followed the task through with debug and its getting to the execute task methotd of JControllerLegacy and because the task is not defined in the task map its defaulting to display, hence the SQL error trying to load a group when it doesn't have an ID. Do I need to now register a task in the task map before it will pick it up?
I am officially an idiot! When I just logged back on to see if anyone had responded I saw that I had declared the function as a protected function!! dir! I just copied and pasted from another function and forgot to change its access. I also made a few other changes and now it works quite well!
public function uploadsave() {
// An array of headers that will need to be entered into a seperate array to allow entry as JSON
$detail_headers = array(
'agm_date',
'preferred_media'
);
$app = JFactory::getApplication();
$lang = JFactory::getLanguage();
$model = $this->getModel();
$path = JPATH_COMPONENT . '/controllers/groupdata.csv';
//Load the file and pass each line into an array.
$rows = array_map('str_getcsv', file($path));
//Take out the first line as it is the headers.
$header = array_shift($rows);
//turn each of the arrays into an entry
foreach ($rows as $row) {
$entry = array_combine($header, $row);
foreach ($entry as $key => $value) {
//separate each of the entries that need to be entered into an array to be stored as JSON
if(in_array($key, $detail_headers)){
$details[$key]= $value;
unset($entry[$key]);
}
}
$entry['details'] = $details;
$recordId = 'id';
// Populate the row id from the session.
$entry[$key] = $recordId;
//Save each one
if (!$model->save($entry))
{
// Redirect back to the edit screen.
$this->setError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError()));
$this->setMessage($this->getError(), 'error');
return false;
}
$this->setMessage(
JText::_(
($lang->hasKey($this->text_prefix . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS')
? $this->text_prefix
: 'JLIB_APPLICATION') . ($recordId == 0 && $app->isSite() ? '_SUBMIT' : '') . '_SAVE_SUCCESS'
)
);
}
// Redirect to the list screen.
$this->setRedirect(
JRoute::_(
'index.php?option=' . $this->option . '&view=' . $this->view_list
. $this->getRedirectToListAppend(), false
)
);
}

Insert PHP code In WordPress Page and Post

I want to know the visitor country using PHP and display it in on a WordPress Page. But when I add PHP code to a WordPress page or post it gives me an error.
How can we add PHP code on WordPress pages and posts?
<?PHP
try
{
function visitor_country()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
$result = "Unknown";
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
$ip_data = #json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
if($ip_data && $ip_data->geoplugin_countryName != null)
{
$result = array('ip' => $ip,
'continentCode' => $ip_data->geoplugin_continentCode,
'countryCode' => $ip_data->geoplugin_countryCode,
'countryName' => $ip_data->geoplugin_countryName,
);
}
return $result;
}
$visitor_details = visitor_country(); // Output Country name [Ex: United States]
$country = $visitor_details['countryName'];
WordPress does not execute PHP in post/page content by default unless it has a shortcode.
The quickest and easiest way to do this is to use a plugin that allows you to run PHP embedded in post content.
There are two other "quick and easy" ways to accomplish it without a plugin:
Make it a shortcode (put it in functions.php and have it echo the country name) which is very easy - see here: Shortcode API at WP Codex
Put it in a template file - make a custom template for that page based on your default page template and add the PHP into the template file rather than the post content: Custom Page Templates
You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.
The easiest solution for this is creating a shortcode. Then you can use something like this
function input_func( $atts ) {
extract( shortcode_atts( array(
'type' => 'text',
'name' => '',
), $atts ) );
return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );
See the Shortcode_API.
Description:
there are 3 steps to run PHP code inside post or page.
In functions.php file (in your theme) add new function
In functions.php file (in your theme) register new shortcode which call your function:
add_shortcode( 'SHORCODE_NAME', 'FUNCTION_NAME' );
use your new shortcode
Example #1: just display text.
In functions:
function simple_function_1() {
return "Hello World!";
}
add_shortcode( 'own_shortcode1', 'simple_function_1' );
In post/page:
[own_shortcode1]
Effect:
Hello World!
Example #2: use for loop.
In functions:
function simple_function_2() {
$output = "";
for ($number = 1; $number < 10; $number++) {
// Append numbers to the string
$output .= "$number<br>";
}
return "$output";
}
add_shortcode( 'own_shortcode2', 'simple_function_2' );
In post/page:
[own_shortcode2]
Effect:
1
2
3
4
5
6
7
8
9
Example #3: use shortcode with arguments
In functions:
function simple_function_3($name) {
return "Hello $name";
}
add_shortcode( 'own_shortcode3', 'simple_function_3' );
In post/page:
[own_shortcode3 name="John"]
Effect:
Hello John
Example #3 - without passing arguments
In post/page:
[own_shortcode3]
Effect:
Hello
When I was trying to accomplish something very similar, I ended up doing something along these lines:
wp-content/themes/resources/functions.php
add_action('init', 'my_php_function');
function my_php_function() {
if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
// add desired php code here
}
}

Drupal SEO page titles

I am trying to list a few games, each, on individual pages. While a game page is opened into a new window the head title of page (< title>) is set to games page header (< h1> My Game). Also to list all game types I am using quick tabs.
From 12 types of games only at 2 of them the title is settled correctly and my problem is that I don't know from where it comes. I have tried to var_dump() all the headers and all of them are returning the same thing "Game" not the title/heading from db.
Where should I look or what would be the next step ?
$metaTitle = $page['content']['metatags']['global']['title']['#attached']['metatag_set_preprocess_variable'][0][2];
$metaTitle = str_replace(' | SuperCasino.com', '', $metaTitle);
Where should I look or what would be the next step ?
Here is my preprocess page code
function desktop_preprocess_page(&$vars, $hook) {
if (isset($vars['node_title'])) {
$vars['title'] = $vars['node_title'];
}
// Adding a class to #page in wireframe mode
if (theme_get_setting('wireframe_mode')) {
$vars['classes_array'][] = 'wireframe-mode';
}
// Adding classes wether #navigation is here or not
if (!empty($vars['main_menu']) or !empty($vars['sub_menu'])) {
$vars['classes_array'][] = 'with-navigation';
}
if (!empty($vars['secondary_menu'])) {
$vars['classes_array'][] = 'with-subnav';
}
// Page template suggestions based off of content types
if (isset($vars['theme_hook_suggestions']['node'])) {
$vars['theme_hook_suggestions'][] = 'page__type__'. $vars['node']->type;
$vars['theme_hook_suggestions'][] = "page__node__" . $vars['node']->nid;
}
// Add first/last classes to node listings about to be rendered.
if (isset($vars['page']['content']['system_main']['nodes'])) {
// All nids about to be loaded (without the #sorted attribute).
$nids = element_children($vars['page']['content']['system_main']['nodes']);
// Only add first/last classes if there is more than 1 node being rendered.
if (count($nids) > 1) {
$first_nid = reset($nids);
$last_nid = end($nids);
$first_node = $vars['page']['content']['system_main']['nodes'][$first_nid]['#node'];
$first_node->classes_array = array('first');
$last_node = $vars['page']['content']['system_main']['nodes'][$last_nid]['#node'];
$last_node->classes_array = array('last');
}
}
//var_dump($vars['theme_hook_suggestions']);die();
// Page template suggestions based off URL alias
if (module_exists('path')) {
//$alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));
$alias = request_path();
if ($alias != $_GET['q']) {
//echo'here';die;
$template_filename = 'page';
foreach (explode('/', $alias) as $path_part) {
$template_filename = $template_filename . '__' . str_replace('-','_',$path_part);
$vars['theme_hook_suggestions'][] = $template_filename;
//var_dump($template_filename);
}
}
}
You can use drupal_set_title(YOUR_TITLE) for the different pages.
drupal_set_title($title = NULL, $output = CHECK_PLAIN)
https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_set_title/7
From the theme level, you can use this code in your template.php:
function MYTHEMENAME_preprocess_page(&$vars, $hook) {
$vars['title'] = $custom_title';
$vars['head_title'] = $custom_title;
}
For Drupal 7 its is :
$vars['site_name']

Categories