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
}
}
Related
I have this code that I want to add in single.php using a custom plugin.
here is the code:
<?php
echo "Facebook: ". $facebook_like_share_count ("$url"). "<br>";
echo "Pinterest: ". $pinterest_pins ("$url") . "<br>";
echo "Google+: ". $google_plusones ("$url") . "<br>";
?>
I want to print this things in single.php when install my custom plugin.
There is two options possible.
Option 1) Create a short code
function bartag_func( $atts ) {
echo "Facebook: ". $facebook_like_share_count ("$url"). "<br>";
echo "Pinterest: ". $pinterest_pins ("$url") . "<br>";
echo "Google+: ". $google_plusones ("$url") . "<br>";
}
add_shortcode( 'social', array( &$this, 'bartag_func' ));
Your short code with be [social]
Option 2 ) Apply the filter on the content
/**
* summary
*/
class WP_Custom_Data
{
/**
* summary
*/
public function __construct()
{
//Here you can add for shortcode as well
add_filter('the_content', array($this, 'wpdev_before_after'));
}
public function wpdev_before_after($content) {
$url = "xyzurl";
$api = file_get_contents( 'http://graph.facebook.com/?id=' . $url );
$count = json_decode( $api );
$beforecontent = $count->share->share_count;
$fullcontent = $beforecontent . $content;
return $fullcontent;
}
// here you can call the shortcode function as well
}
$wpspw_pro_script = new WP_Custom_Data();
Note : I am not sure what you are doing here with function because you have set the variable as a function. according to me it must give you the error.
Anyways, according to me there two option possible here and i have given you the options for same
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;
}
}
I have this very simple question, but I am searching for hours now, and cannot find the answer.
With my function wzd_url() I make my urls.
For example wzd_url(2) gives me: http://www.mywebsite.com/douchedeur-glassoort
I use this function in my whole project and works fine. But know I want to use this function as follows:
echo = 'test';
or:
function output() {
$output = 'test';
echo $output;
}
output();
it outputs: http://www.mywebsite.com/douchedeur-matentest
And I read some other articles about this subject, and they said I need to change echo to return in my wzd_url() function, but if I do that this function doesn't work anymore.
Can someone help me with this?
In this array I store some data for my pages:
$wzd_pages = array(
0 => array('Intro', 'douchedeur-intro'),
1 => array('Maten', 'douchedeur-maten'),
2 => array('Glassoort', 'douchedeur-glassoort'),
3 => array('Scharnieren', 'douchedeur-scharnieren', 'Scharnieren en draairichting'),
4 => array('Deuropener', 'douchedeur-deuropener'),
5 => array('Coating', 'douchedeur-coating'),
6 => array('Prijs / Bestellen', 'douchedeur-prijs'));
With this function I make my URLs:
// URL
function wzd_url($page) {
global $wzd_pages;
echo bloginfo('wpurl') . '/' . $wzd_pages[$page][1];
}
if you change echo to return, your function will "return" that link but it wont show it. Then you need echo in you template for example:
echo test
In summary - when you need to move echo from your function to your template
I suggest you create 2 function as below :-
function wzd_url($page) {
global $wzd_pages;
if(is_array($wzd_pages[$page]) && count($wzd_pages[$page])){
$_return['url'] = bloginfo('wpurl') . '/' . $wzd_pages[$page][1];
$_return['text'] = $wzd_pages[$page][0];
return $_return;
}else{
return false;
}
}
function anchor($page){
if($url = wzd_url($page)){
?>
<?php echo $url['text']?>
<?php
}
}
I needed to modify the wzd_url(); function, because it uses bloginfo();, and this function prints the string. So I need get_bloginfo(); or better: site_url();
// URL
function wzd_url($page) {
global $wzd_pages;
echo siteurl('wpurl' . '/' . $wzd_pages[$page][1] );
}
I've written a wordpress plugin that requires our writers to pick a topic from an external site. It will not allow the writer to publish the article unless a topic from the external site is associated with it. When the article is published, the topic they chose is updated on the external site and, therefore, on an option to select again.
This all works as expected. My problem is that when a user updates an article that has already been published, and therefore, the topic is no longer an option to choose, the plugin stops them from updating because there is no topic.
My question is: Is there a way to ensure the plugin only runs when a post is initially published, not when it is updated?
Here is the code (with parts removed):
<?php
*/
Plugin Name: name
Description: Make sure writers articles are associated with a name topic.
*/
add_action('add_meta_boxes','name_add_meta_boxes');
add_action('save_post', 'complete_name_topic');
function name_add_meta_boxes() {
add_meta_box(
'name',
'name',
'name_html',
'post',
'normal'
);
}
function name_html($post){
wp_nonce_field(plugin_basename(__FILE__), 'name_nonce');
$current_user = wp_get_current_user();
$f_name = utf8_encode($current_user->user_firstname);
$l_name = utf8_encode($current_user->user_lastname);
if(!$f_name || !$l_name){
$display_name = str_replace(' ', '%20', $current_user->display_name);
}else{
$display_name = $f_name.'%20'.$l_name;
}
$bar = json_decode(www.example.com));
$foo = get_object_vars($bar);
echo '<select name="name"><option value="">Choose name Topic</option>';
foreach($foo as $id => $topic){
echo "<option value='$id'>$topic</option>";
}
echo '</select>';
}
function complete_name_topic($post_id) {
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
if(!wp_verify_nonce($_POST['name_nonce'], plugin_basename(__FILE__)))
return;
$id = wp_is_post_revision($post_id);
if(!$id){
$permalink = get_permalink($post_id);
}else{
$permalink = get_permalink($id);
}
if(!isset($_POST['name']) || empty($_POST['name'])){
$message = 72;
global $wpdb;
$wpdb->update($wpdb->posts, array('post_status' => 'pending'), array('ID' => $post_id));
add_filter('redirect_post_location', create_function('$location', 'return add_query_arg("message", "'.$message.'", $location);'));
}else{
$ch = curl_init('www.example.com');
curl_setopt($ch, CURLOPT_POSTFIELDS, "URL=$permalink");
curl_exec($ch);
curl_close($ch);
}
}
add_filter('post_updated_messages', 'name_error_message');
function name_error_message($messages){
$messages['post']['**'] = 'A name topic must be associated with this post.';
return $messages;
}
if you update_post_meta the first time through, you can get_post_meta to discover whether that has happened already on subsequent updates.
I have my homepage http://www.faberunashop.com set up as a directory. When you click on the post image, it takes you over to the artists site. Here is the code that I used to make this happen by adding it to the functions.php:
function print_post_title() {
global $post;
$thePostID = $post->ID;
$post_id = get_post($thePostID);
$title = $post_id->post_title;
$perm = get_permalink($post_id);
$post_keys = array(); $post_val = array();
$post_keys = get_post_custom_keys($thePostID);
if (!empty($post_keys)) {
foreach ($post_keys as $pkey) {
if ($pkey=='url1' || $pkey=='title_url' || $pkey=='url_title') {
$post_val = get_post_custom_values($pkey);
}
}
if (empty($post_val)) {
$link = $perm;
} else {
$link = $post_val[0];
}
} else {
$link = $perm;
}
echo '<h2>'.$title.'</h2>';
}
Now I want to do the same to my search and archive page. What do I adjust to make them behave the same?
I suppose that you use WordPress.
In that case you can change the layout and the behavior of your search results by creating a file with name search.php into your theme for your search results, and another file for archives that called archives.php.
For more information about Template Hierarchy for WordPress you can find here http://codex.wordpress.org/Template_Hierarchy