WordPress Custom Post Titles - php

I am looking for a method to change how a post title is shown on screen in WordPress that only applies to the post header.
I am trying to display Name, Gender, Age in the post title. The name I display is the current post title, and I am trying to add gender and age to this for display purposes only.
I have used the current code, but it applies to everything in my theme that uses the tile, and adds these fields to menu items as well.
I have not edited any of the PHP files within the theme, and would like to avoid that and do it via a function
Here is my code:
add_filter( 'the_title', function( $title ) {
$gender = get_field('gender');
$dob = get_field('date_of_birth');
$birthday = new DateTime($dob);
$interval = $birthday->diff(new DateTime);
if ('babysitters' == get_post_type()) {
$temp_title = $title;
$bbstitle = $temp_title .', ' .$gender .', ' .$interval->y;
return $bbstitle;
}
return $title;
} );
What am I doing where it replaces all titles with these appended fields, and not just the post header

UPDATED
function text_domain_custom_title($title) {
global $post;
if ($post->post_type == 'babysitters') {
$gender = get_field('gender', $post->ID);
$dob = get_field('date_of_birth', $post->ID);
$birthday = new DateTime($dob);
$interval = $birthday->diff(new DateTime);
$bbstitle = $title . ', ' . $gender . ', ' . $interval->y;
return $bbstitle;
} else {
return $title;
}
}
add_filter('the_title', 'text_domain_custom_title', 10, 2);
This code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Please note: This code is not tested, but it should work.
Reference:
get_field
How to append text to title of Custom Post Type post (without affecting all titles on page)?

<?php
add_filter('the_title', 'new_title', 10, 2);
function new_title($title, $id) {
if('babysitters' == get_post_type($id)){
$gender = get_field('gender');
$dob = get_field('date_of_birth');
$birthday = new DateTime($dob);
$interval = $birthday->diff(new DateTime);
$newtitle = $title .', ' .$gender .', ' .$interval->y;
}
else{
$newtitle = $title;
}
return $newtitle;
}
?>

Related

Can't display footer (wordpress)

Problem:
run_overview() displays account_page-overview.php well.
The problem is that it blocks footer(), so the footer part disappears on frontend.
When I remove 'require $template;' of the run_overview(), it shows a footer part well, but doesn't show run_overview() part.
Action I took:
I tried changing the following code (and removed require $template;), but it doesn't display run_overview() part.
include locate_template('public/views/account_page-overview.php', false, false);
Need Help:
Would you please let me know if there is another method to display both run_overview() and footer()?
PHP Code:
private function run_overview(){
/*
* #param none
* #return none (print html)
*/
global $indeed_db;
$post_overview = get_user_meta($this->uid, 'uap_overview_post', true);
if ($post_overview && $post_overview!=-1){
//print the post for user
$post = get_post($post_overview);
$data['message'] = $post->post_content;
} else {
//predifined message
$data['message'] = uap_replace_constants($this->account_page_settings['uap_tab_overview_content'], $this->uid);
$data['message'] = stripslashes($data['message']);
$data['message'] = uap_correct_text($data['message']);
}
$data['title'] = $this->account_page_settings['uap_tab_overview_title'];
$data['stats'] = $indeed_db->get_stats_for_payments($this->affiliate_id);
$data['stats']['currency'] = get_option('uap_currency');
$data['help_url'] = $url = add_query_arg('uap_aff_subtab', 'help', $this->account_page_base_url);
$data['statsForLast30'] = $indeed_db->getReferralsAmountForLastDays( $this->affiliate_id, 30 );
$data['referralsStats'] = $indeed_db->get_stats_for_reports( 'last_month', $this->affiliate_id );
$data['referralsExtraStats'] = $indeed_db->get_referral_report_by_date( $this->affiliate_id, date( 'Y-m-d h:i:s', time() - 30 * 24 * 60 * 60 ), date( 'Y-m-d h:i:s', time() ) );
$this->print_top_messages();
$fullPath = UAP_PATH . 'public/views/account_page-overview.php';
$searchFilename = 'account_page-overview.php';
$template = apply_filters('uap_filter_on_load_template', $fullPath, $searchFilename );
require $template;
}
private function footer(){
global $indeed_db;
$data['footer_content'] = uap_replace_constants($this->account_page_settings['uap_ap_footer_msg'], $this->uid);
$data['footer_content'] = stripslashes($data['footer_content']);
$fullPath = UAP_PATH . 'public/views/account_page-footer.php';
$searchFilename = 'account_page-footer.php';
$template = apply_filters('uap_filter_on_load_template', $fullPath, $searchFilename );
require $template;
}
Thank you.

PHP Syntax error issue, display title correctly using parameters

I have a php Code as below but unable to display title with correct php value
For instance on standalone basis it displays correct data as
$this->CatName; - Displays category
$this->prodDet->prod_name; - Displays Product Name
$this->prodDet->v_location; - Displays Location
I want to create a combined title as
Used <catname> <prod_name> for sale in <v_location>
Like
Used Fisher Milk Bottle for sale in Capetown
But when i modify code in
$title = 'Used' ($this->CatName $this->prodDet->prod_name) 'for Sale in' ($this->prodDet->v_location);
It shows syntax error and does not work
Here is complete code
<?php
defined('_JEXEC') or die;
jimport('joomla.application.component.view');
/**
* Prepares the document
*
* #return void
*
* #throws Exception
*/
protected function _prepareDocument()
{
$app = JFactory::getApplication();
$menus = $app->getMenu();
$title = null;
$menu = $menus->getActive();
if ($menu) {
$this->params->def('page_heading', $this->params->get('page_title', $menu->title));
} else {
$this->params->def('page_heading', JText::_('COM_USEDCAR_DEFAULT_PAGE_TITLE'));
}
$title = $this->params->get('page_title', '');
if (empty($title)) {
$title = $app->get('sitename');
} elseif ($app->get('sitename_pagetitles', 0) == 1) {
$title = JText::sprintf('JPAGETITLE', $app->get('sitename'), $title);
} elseif ($app->get('sitename_pagetitles', 0) == 2) {
$title = JText::sprintf('JPAGETITLE', $title, $app->get('sitename'));
}
$title = $this->CatName;
$this->document->setTitle($title);
}
?>
Can any one help how to display correct title
Use the concatenation operator . , read more here
change
$title = 'Used' ($this->CatName $this->prodDet->prod_name) 'for Sale in' ($this->prodDet->v_location);
to
$title = 'Used' . ($this->CatName .' '.$this->prodDet->prod_name). 'for Sale in' . ($this->prodDet->v_location);
Use concatenation(.) operator there like below:-
$title = 'Used '.($this->CatName.' '.$this->prodDet->prod_name).' for Sale in '.($this->prodDet->v_location);
Note:- Also add spaces in between variables and string so that output look bit good.(I have already did that in my solution)
Reference:-String Operators

Using Wordpress Plugin Function in a Widget

I have a Wordpress plugin with a file (userinfo.php) that processes a function -- generateUserInfo(). I want to use this function on a sidebar widget. I'm unclear on exactly how to get that done.
Here is the code from userinfo.php inside of my plugin.
require_once("../../../wp-load.php");
//need the current user's ID
$user = get_current_user_id();
$meetings = generateUserInfo($user, 4, 3, 'meetings');
$events = generateUserInfo($user, 6, 2, 'events');
function generateUserInfo($user,$taxonomy_id,$num_required_events,$event_type){
global $wpdb, $table_prefix;
$num_total_events = 0;
$num_actual_events = 0;
//Get the name of the taxonomy term for events (ID: 6)
$events = get_term_by('term_taxonomy_id', $taxonomy_id, 'events_categories');
$event_category_name = $events->name;
$event_posts = get_posts(array('post_type' => 'ai1ec_event', 'events_categories' => $event_category_name, 'posts_per_page' => -1));
foreach($event_posts as $event){
$attended_events_query = $wpdb->get_results("SELECT vote FROM ".$table_prefix."attendance_list WHERE post = " . $event->ID . " AND user = " . $user);
if(count($attended_events_query)>0 && is_array($attended_events_query)) {
foreach($attended_events_query as $evt){
//add to the acutal events attended
if($evt->vote == 1) $num_actual_events++;
}
}
$num_total_events++;
}
$events_msg = '<div>You have attended <br> <span class="big-num">'. $num_actual_events . '</span> / ' . $num_total_events . ' ' . $event_type . '</br>('. $num_required_events.' required)<br><br></div>';
echo $events_msg;
return $events_msg;
}
And here is the beginning of my widget:
function your_widget_display($args) {
extract($args);
echo $before_widget;
echo $before_title . 'Attendance Tracker' . $after_title;
echo $after_widget;
// print some HTML for the widget to display here
echo 'whatever';
}
wp_register_sidebar_widget(
'yac_attendance_widget', // your unique widget id
'YAC Member Attendance Tracker', // widget name
'your_widget_display', // callback function
array( // options
'description' => 'Description of what your widget does'
)
);
Just before echo $after_widget;, add the following
if(function_exists('generateUserInfo')) {
generateUserInfo();
}

WordPress theme is eliminating my PayPal purchase link's ampersand and all text afterwards

I've encountered a strange error in a theme called "Faith" (by Chimpstudio). When user publishes or updates the page, the PayPal link doesn't write to the database properly.
As far as I'm aware, the value being written to the database is contained in an XML array, like so:
noSimpleXMLElement Object ( [0] => https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick )
The link that should be publishing/updating (before hitting Publish/Update) is:
https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=XXXXXXXXXXXXX
The "&hosted_button_id=XXXXXXXXXXXXX" is not being saved, which means users cannot purchase my client's product.
Potential solution: I've been digging through the theme's .php files, looking for an opportunity to intercept the value being passed to the WordPress database. The idea was to wrap/encode the variable before it gets send to the WP database, with the hope that the entire URL string remains unchanged at the "&hosted_button_id=XXXXXXXXXXXXX" part of the URL.
Any solutions or ideas which may help?
EDIT: This may be a relevant piece of code from the admin_functions.php file:
function events_meta_save($post_id) {
global $wpdb;
if (empty($_POST["event_ticket_price"])){ $_POST["event_ticket_price"] = "";}
if (empty($_POST["event_social_sharing"])){ $_POST["event_social_sharing"] = "";}
if (empty($_POST["event_buy_now"])){ $_POST["event_buy_now"] = "";}
if (empty($_POST["event_phone_no"])){ $_POST["event_phone_no"] = "";}
if (empty($_POST["switch_footer_widgets"])){ $_POST["switch_footer_widgets"] = "";}
if (empty($_POST["event_start_time"])){ $_POST["event_start_time"] = "";}
if (empty($_POST["event_end_time"])){ $_POST["event_end_time"] = "";}
if (empty($_POST["event_all_day"])){ $_POST["event_all_day"] = "";}
if (empty($_POST["event_address"])){ $_POST["event_address"] = "";}
if (empty($_POST["event_ticket_options"])){ $_POST["event_ticket_options"] = "";}
if (empty($_POST["event_map"])){ $_POST["event_map"] = "";}
$sxe = new SimpleXMLElement("<event></event>");
$sxe->addChild('event_ticket_price', $_POST['event_ticket_price'] );
$sxe->addChild('event_social_sharing', $_POST["event_social_sharing"]);
$sxe->addChild('event_buy_now', $_POST["event_buy_now"]);
$sxe->addChild('event_phone_no', $_POST["event_phone_no"]);
$sxe->addChild('switch_footer_widgets', $_POST["switch_footer_widgets"]);
$sxe->addChild('event_start_time', $_POST["event_start_time"]);
$sxe->addChild('event_end_time', $_POST["event_end_time"]);
$sxe->addChild('event_all_day', $_POST["event_all_day"]);
$sxe->addChild('event_ticket_options', $_POST["event_ticket_options"]);
$sxe->addChild('event_address', $_POST["event_address"]);
$sxe->addChild('event_map', $_POST["event_map"]);
echo "<pre>BPOST: ".print_r($_POST, true)."</pre>";
print_r($sxe);
$sxe = save_layout_xml($sxe);
print_r($sxe);
update_post_meta($post_id, 'cs_event_meta', $sxe->asXML());
}
Additionally, here's more code for the XML side from the events.php file:
// event custom fields start
add_action( 'add_meta_boxes', 'cs_event_meta' );
function cs_event_meta()
{
add_meta_box( 'event_meta', 'Event Options', 'cs_event_meta_data', 'events', 'normal', 'high' );
}
function cs_event_meta_data($post) {
$cs_event_meta = get_post_meta($post->ID, "cs_event_meta", true);
global $cs_xmlObject;
if ( $cs_event_meta <> "" ) {
$cs_xmlObject = new SimpleXMLElement($cs_event_meta);
$event_ticket_price = $cs_xmlObject->event_ticket_price;
$event_social_sharing = $cs_xmlObject->event_social_sharing;
$event_start_time = $cs_xmlObject->event_start_time;
$event_end_time = $cs_xmlObject->event_end_time;
$event_all_day = $cs_xmlObject->event_all_day;
$event_address = $cs_xmlObject->event_address;
$event_loc_lat = $cs_xmlObject->event_loc_lat;
$event_loc_long = $cs_xmlObject->event_loc_long;
$event_loc_zoom = $cs_xmlObject->event_loc_zoom;
$testVar = $cs_xmlObject->event_buy_now;
if (strstr($cs_xmlObject->event_buy_now, "&"))
{
echo "yes"; //$event_buy_now = ($cs_xmlObject->event_buy_now . 'FINDME(yes)');
print_r ($testVar);
}
else
{
echo "no"; //$event_buy_now = ($cs_xmlObject->event_buy_now . 'FINDME(no)');
print_r ($testVar);
print_r ($cs_xmlObject);
}
$event_ticket_options = $cs_xmlObject->event_ticket_options;
$event_map = $cs_xmlObject->event_map;
}
else {
$event_ticket_price = '';
$slider_id = '';
$event_social_sharing = '';
$event_related = '';
$event_start_time = '';
$event_end_time = '';
$event_all_day = '';
$event_address = '';
$event_loc_lat = '';
$event_loc_long = '';
$event_loc_zoom = '';
$inside_event_related_post_title = '';
$event_map = '';
$event_buy_now = '';
$event_ticket_options = '';
}
NOTE: Both of these code snippets are located in the parent theme's /include/ directory. At this point, there is no child theme -- and if necessary, a child theme will be created to implement these updates.
Just use jQuery and .change() to detect new content in an input. When the field gets changed, have it change the & to & amp; Might be a dirty hack, but if this is standing between you and payday, have at 'er.

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
}
}

Categories