If last name exists else first name | Wordpress - php

I'm a completely newbie and trying around in wordpress atm.
I have this function to get first name:
function get_first_name () {
$user_data = get_userdata(get_current_user_id());
return $user_data->first_name;
}
to get the users first name (and display it somewhere afterwards). Now i want to work it like if the user has registered only with his first name it should only get the first name but if he also registered with lastname it should only (!) get last name and ignore the first name.
Can someone help me with this?

A simple ternary statement should do it for you
return $user_data->last_name != '' ? $user_data->last_name : $user_data->first_name;
It is like the longer IF
if ($user_data->last_name != '') {
return $user_data->last_name;
} else {
return $user_data->first_name;
}

Related

Passing multiple variables through a URL using OR instead of AND (&)

I am trying to set up a website that will have a drop-down menu, and each option will direct you to a subset of the database. For example, people in the state of Ohio, or the state of Michigan, etc. I have some people who want to be pulled no matter what the state and there is a category called all_states. I've seen how I can add variables to the URL (example: http://www.website.com/page.htm?OH=1) I've also seen examples where two variables are set (example: http://www.website.com/page.htm?OH=1&all_states=1). But how do I set it up so that only one condition needs to be met, effectively an OR instead of an AND? I want to be able to set up links to call data, for example, for those where Ohio is true (OH=1) OR all_states is true (all_states=1) because some people did not specify a particular state but will help in all states so I need to be able to pull in each list in one URL command.
The & symbol in the URL is just a separator between variables, and does not mean that anything is required. Your PHP (or whatever is parsing the GET variables) is what should check for that.
For example, you could parse it by writing something like (in PHP):
if(isset($_GET['all_states'])){
// do something for all states //
}else{
$states = ["OH", "CA", ...];
// recurse through state abbreviations //
foreach($state in $states){
if(isset($_GET[$state])){
// do something for individual state //
}
}
}
In Javascript:
$(document).ready(function(e){
var allStates = getParameterByName('all_states');
if(isset(allStates)){
// do something for all states //
}else{
// check & do something for individual states //
}
});
function isset(obj){
return typeof(obj) !== 'undefined' && obj != null && obj !== '';
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Although I would personally recommend using a state variable, like this:
State Variable for Individual State: http://whatever.com/something.php?state=OH
State Variable for All States: http://whatever.com/something.php?state=all
And just check what the state variable is in your PHP instead.

Add/Replace URL GET parameter depending on current URL

I’ve tried for some time now to solve what probably is a small issue but I just can’t seem get my head around it. I’ve tried some different approaches, some found at SO but none has worked yet.
The problem consists of this:
I’ve a show-room page where I show some cloth. On each single item of cloth there is four “views”
Male
Female
Front
Back
Now, the users can filter this by either viewing the male or female model but they can also filter by viewing front or back of both gender.
I’ve created my script so it detects the URL query and display the correct data but my problem is to “build” the URL correctly.
When firstly enter the page, the four links is like this:
example.com?gender=male
example.com?gender=female
example.com?site=front
example.com?site=back
This work because it’s the “default” view (the default view is set to gender=male && site=front) in the model.
But if I choose to view ?gender=female the users should be able to filter it once more by adding &site=back so the complete URL would be: example.com?gender=female&site=back
And if I then press the link to see gender=male it should still keep the URL parameter &site=back.
What I’ve achived so far is to append the parameters to the existing URL but this result in URL strings like: example.com?gender=male&site=front&gender=female and so on…
I’ve tried but to use the parse_url function, the http_build_query($parms) method and to make my “own” function that checks for existing parameters but it does not work.
My latest try was this:
_setURL(‘http://example.com?gender=male’, ‘site’, ‘back’);
function _setURL($url, $key, $value) {
$separator = (parse_url($url, PHP_URL_QUERY) == NULL) ? '?' : '&';
$query = $key."=".$value;
$url .= $separator . $query;
var_dump($url); exit;
}
This function works unless the $_GET parameter already exists and thus should be replaced and not added.
I’m not sure if there is some “best practice” to solve this and as I said I’ve looked at a lot of answers on SO but none which was spot on my issue.
I hope I’ve explained myself otherwise please let me know and I’ll elaborate.
Any help or advice would be appreciated
You can generate the links dynamically using the following method:
$frontLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=front':'mydomain.com?site=front';
$backLink = (isset($_GET['gender'])) ? 'mydomain.com?gender='.$_GET['gender'].'&site=back':'mydomain.com?site=back';
This is a 1 line if statement which will set the value of the variables $frontLink and $backlink respectively. The syntax for a 1 line if statement is $var = (if_statement) ? true_result:false_result; this will set the value of $var to the true_result or false_result depending on the return value of the if statement.
You can then do the same for the genders:
$maleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=male&site='.$_GET['site']:'mydomain.com?gender=male';
$femaleLink = (isset($_GET['site'])) ? 'mydomain.com?gender=female&site='.$_GET['site']:'mydomain.com?gender=female';
Found this by searching for a better solution then mine and found this ugly one (That we see a lot on the web), so here is my solution :
function add_get_parameter($arg, $value)
{
$_GET[$arg] = $value;
return "?" . http_build_query($_GET);
}
<?php
function requestUriAddGetParams(array $params)
{
$parseRes=parse_url($_REQUEST['REQUEST_URI']);
$params=array_merge($_GET, $params);
return $parseRes['path'].'?'.http_build_query($params);
}
?>
if(isset($_GET['diagid']) && $_GET['diagid']!='') {
$repParam = "&diagid=".$_GET['diagid'];
$params = str_replace($repParam, "", $_SERVER['REQUEST_URI']);
$url = "http://".$_SERVER['HTTP_HOST'].$params."&diagid=".$ID;
}
else $url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']."&diagid=".$ID;

Redirect depending on URI Segment

I am using Codeigniter and want to have SEO-friendly URLs. There will be 2 types of URI segments, http://www.domain.com/view/193847 and http://www.domain.com/view/193847-canon-5d-mark-iii.
If the first URL is used, function view_mini is called and passed the product id 193847. If the 2nd one is used, function view_full will be called and passed the same product id 193847.
Problem: How can I differentiate between the 2 URLs? Or is this an inferior approach to solve the problem?
PHP How should the if condition be structured?
function view($pid) {
if($this->uri->segment(2) == something) {
$this->view_mini($pid);
} else {
$this->view_full($pid);
}
}
function view_mini($pid) {
// ...
}
function view_full($pid) {
// ...
}
EDIT
I am using URL routing to route http://www.domain.com/controllername/view/1234 to http://www.domain.com/view/1234
you can use the regular expression to check the segment if it has anything other than numbers, then you can execute the view that you want for example
$pattern = '\d[0-9][^a-zA-Z]';
$url = $this->uri->segment(2);
if(preg_match($pattern,$url))
{
//this will match only the numbers
$this->view_mini($pid);
} else {
$this->view_full($pid);
}
i hope this will help ..
Is there any definitive structure to the different URLs?
ie.
http://www.domain.com/view/[numbers]-[text]
If so, you could test the URL for that dash between the numbers and the dash?
Edit: un-tested
$route["view/(\d+)"] = "class/view_mini/$1";
$route["view/(\d+)-([\w'-]*)?/g"] = "class/view_full/$1/$2";
Use
$result = explode('-', $this->uri->segment(1));
If(isset($result[1]))
{
// show full view
} else {
// show mini view
}
$pid will always be $result[0]

saving a field to upper case in drupal 6?

In drupal event creation I have a cck text field called person.How to force the person field to save(in db) in upper case only ?
Check out hook_nodeapi (http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_nodeapi/6)
You should be able to write a function in a module something that looks a little like this:
function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
if ($op == 'presave' && $node->type == 'event') {
$person = strtoupper($node->field_person[0]['value']);
$node->field_person[0]['value'] = $person;
}
}
Where it says event, just replace with your machine-friendly content type name, and where it says field_person, replace this with the machine name for your person field (probably field_person in your case.
If you wanna see if it works then put this in your the code before the end of the if statement (should be your CCK field all in uppercase..probably with a 1 after it, but just ignore that, it's just the die() :-))
die(print_r($person));
for drupal 7 that works :
function mymodule_node_presave($node) {
if ($node->type == ('article') {
$node->title = ucfirst($node->title);
}
}

Better Capture to Session Affiliate Id from GET in PHP

Can someone help me clean this up and make it more logical? I'm fried right now and can't seem to get a good line of code written :)
I'm trying to capture affiliate id from urls like ?aid=3056677. The idea is IF aff id is set in GET that takes precedence, the session and finally cookie with least. Also, we don't want to set an aff id that does not exist.
Do you know of a more tried and true method of doing this?
session_start(); // start session
// affiliate id
$g_aid = (isset($_GET['aid']) && $_GET['aid'] != '') ? trim($_GET['aid']) : false;
$s_aid = (isset($_SESSION['aid']) && $_SESSION['aid'] != '') ? trim($_SESSION['aid']) : false;
$c_aid = (isset($_COOKIE['aid']) && $_COOKIE['aid'] != '') ? trim($_COOKIE['aid']) : false;
if($g_aid !== false) // use get if set
$aid = $g_aid;
elseif($s_aid !== false) // next use session if get not set
$aid = $s_aid;
elseif($c_aid !== false) // cookie
$aid = $c_aid;
else
$aid = ''; // leave it empty
// if $aid is set is it in the $affiliates array?
//If not use the first key from that array
$aid = (isset($affiliates[$aid])) ? $aid : key($affiliates);
// save it and set it
// (maybe shouldn't be done if already stored?
setcookie('aid', $aid);
$_SESSION['aid'] = $aid;
session_start();
// checks if a field is valid
function isValid($aid) {
return (!empty($aid) && trim($aid) != '');
}
// set the affiliate ID
$aid = isValid($_GET['aid']) ? $_GET['aid'] :
isValid($_SESSION['aid']) ? $_SESSION['aid'] :
isValid($_COOKIE['aid']) ? $_COOKIE['aid'] :
'';
// use first key from array if aid not set
if (!isset($affiliates[$aid])) $aid = key($a);
// save and set
setcookie('aid', $aid);
$_SESSION['aid'] = $aid;
Why would you test for session and cookie, in case you have a valid affiliateID from the $_GET array? ==> Make it progressive so that session is only checked, if no GET was found and cookie is only checked if no session was found.
Don't repeat the validation of the affiliateID. ==> Write a validate function and reuse it, you might want to add more rules later on.
Use curly brackets to make your code more readable
$aid or $aff are BAD variable names, $affiliateID instead is a GOOD one! You don't win anything for writing short variables names but you win a lot with writing self-explanatory code.
Bad example, doesn't talk
if (validate($aff))
Good example, talks to you
if (isValid($affiliationID))
So my proposal for change of the core components:
if (isValid($_GET['aid']))
{
$affiliationID = trim($_GET['aid'];
}
else if (isValid($_SESSION['aid']))
{
$affiliationID = trim($_SESSION'aid'];
}
else if (isValid($_COOKIE['aid']))
{
$affiliationID = trim($_COOKIE['aid'];
}
else
{
throw new Exception('No affiliation ID defined');
}
function isValid($affiliationID)
{
if (empty($affiliationID))
{
return false;
}
else
{
return true;
}
}
Thanks guys this is looking better and better. One point that might clarify for you, is that IF an aff id is given in GET it MUST be a valid one that exists before we possibly wipe out someone else's aff id. Money is involved with each transaction and we want an affiliate to get credit for as long as possible.
Regarding empty it's not too useful since whitespace fools it. So unless you trim before using it, I feel it's not accurate enough. So I don't know about the empty for the GET. It's ok for the others because we've already checked them.
Here's what I have so far from your help (does the complex ternary here break when it finds true? I don't want it to keep executing the line):
session_start(); // start session
$aid = !empty($_GET['aid']) ? trim($_GET['aid']) :
!empty($_SESSION['aid']) ? $_SESSION['aid'] :
!empty($_COOKIE['aid']) ? $_COOKIE['aid'] :
'';
// use first key from array if aid not set
if(!isset($a[$aid])) $aid = key($a);
if(!isset($_SESSION['aid']) || $aid != $_SESSION['aid'])
{
setcookie('aid', $aid);
$_SESSION['aid'] = $aid;
}

Categories