Wordpress custom field echoing whole URL - php

My code is as below:
<?php
if( get_field( "facebook" ) !== '' ): ?>
Facebook
<?php endif;?>
Instead of echoing the field's value which is (wwww.facebook.com), it's echoing it relative to the wordpress website.
Also, is my code efficient? Or is there a simpler way to do it?
Edit: What finally worked for me:
<?php
$website = (get_field('website'));
if(!empty($website)){
$final_url = (!preg_match("~^(?:f|ht)tps?://~i", $website))? 'http://'.$website: $website;
echo "$final_url" . "<br />";
}
?>

you should add http:// on the beggining to make external URLS
Facebook
or add http:// on your advanced custom field in the admin
EDIT:
here is your final code:
$url = the_field('facebook');
if($url!=""){
$final_url = (!preg_match("~^(?:f|ht)tps?://~i", $url))? 'http://'.$url: $url;
echo 'Facebook<br/>';
}
NOTE:
your data wwww.facebook.com has excess w
i appended the code given by #feeela so it would check if http:// is present, thanks to #feeela

Related

Apply php function to shortcode

I'll start by saying I'm fairly new to coding so I'm probably going about this the wrong way.
Basically I've got the below php function that changes urls to the page title of the url instead of a plain web address. So instead of www.google.com it would appear as Google.
<?php
function get_title($url){
$str = file_get_contents($url);
if(strlen($str)>0){
$str = trim(preg_replace('/\s+/', ' ', $str)); // supports line breaks inside <title>
preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title); // ignore case
return $title[1];
}
}
?>
This is great but to implement this I have to use the below code.
echo get_title("http://www.google.com/");
However this just works on a predefined URL. What I have set up on my site at the moment is a shortcode in a html widget.
<a href='[rwmb_meta meta_key="link_1"]'>[rwmb_meta meta_key="link_1"]</a>
This shortcode displays a url/link that is input by the user in the backend of Wordpress and displays it on the frontend as a link. However I want to apply the get_title function to the above shortcode so instead of the web address it shows the page title.
Is this possible?
Thanks in advance.
for name of a url from a link you can use parse_url($url, PHP_URL_HOST);
easier way would be to have an array of links for example
$links[] = 'some1 url here';
$links[] = 'some2 url here';
then just loop your $links array with the function.
foreach($links as $link)get_title($link);
https://metabox.io/docs/get-meta-value/
try:
$files = rwmb_meta( 'info' ); // Since 4.8.0
$files = rwmb_meta( 'info', 'type=file' ); // Prior to 4.8.0
if ( !empty( $files ) ) {
foreach ( $files as $file ) {
echo $file['url'];
}
}

How to strip http://www. from php function leaving only .com

I have a coupon site that display store urls on my store pages. What I want is for only .com at end of each store without showing http:// variations in the beginning
here is my code that displays a store url and I just want domain.com to be displayed instead of http://www.domain.com, also may show as http://domain.com
<p class="store-url"><a href="<?php echo $url_out; ?>" target="_blank"><?php echo $stores_url; ?>
It displays like this because of this function
<div class="store">
<?php // grab the store meta data
$term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
$stores_url = esc_url(get_metadata(APP_TAX_STORE, $term->term_id, 'clpr_store_url', true));
$dest_url = esc_url(get_metadata(APP_TAX_STORE, $term->term_id, 'clpr_store_aff_url', true));
// if there's a store aff link, then cloak it. else use store url
if ($dest_url)
$url_out = esc_url(home_url(CLPR_STORE_REDIRECT_BASE_URL . $term->slug));
else
$url_out = $stores_url;
?>
What can be done................
Quick and dirty - to demonstrate the possible functions...
<?php
function cleanInputString($inputString) {
// lower chars
$inputString = strtolower($inputString);
// remove whitespaces
$inputString = str_replace(' ', '', $inputString);
// check for .com at the end or add otherwise
if(substr($inputString, -4) == '.com') {
return $inputString;
} else {
return $inputString .'.com';
}
}
// example
$inputStrings = array(
'xyzexamp.com',
'xyzexamp',
'xyz examp'
);
foreach($inputStrings as $string) {
echo('input: '. $string .'; output: '. cleanInputString($string) .'<br />');
}
?>
OUTPUT:
input: xyzexamp.com; output: xyzexamp.com
input: xyzexamp; output: xyzexamp.com
input: xyz examp; output: xyzexamp.com
The "right way" is probably to use the PHP URL-processing:
Break the URL up using http://php.net/manual/en/function.parse-url.php
Remove the scheme element of the resulting array using unset
Build it again using http://www.php.net/manual/en/function.http-build-url.php
This is what preg_replace was made for:
<?php
$http_url = 'http://www.somestore.com/some/path/to/a/page.aspx';
$domain = preg_replace('#^https?://(?:www\.)?(.*?)(?:/.*)$#', '$1', $http_url);
print $domain;
?>
This code will print out
somestore.com

How to use else statement in this PHP script to echo HTML table

This script works well unless you put two URLS in that do not have meta tags, then they render in html all wrong.
How can I use the else statement in it so it will stop?
If you want to test it go here: http://php-playground.co.cc/testdir/metaex.php
<form method="get" action=<?php echo "'".$_SERVER['PHP_SELF']."'";?> >
<p>URL of Competitor:</p>
<textarea name="siteurl" rows="10" cols="50">
<?php //Check if the form has already been submitted and if this is the case, display the submitted content. If not, display 'http://'.
echo (isset($_GET['siteurl']))?htmlspecialchars($_GET['siteurl']):"http://";?>
</textarea><br>
<input type="submit" value="Submit">
</form>
<div id="nofloat"></div>
<table>
<?php
function parseUrl($url){
//Trim whitespace of the url to ensure proper checking.
$url = trim($url);
//Check if a protocol is specified at the beginning of the url. If it's not, prepend 'http://'.
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
//Check if '/' is present at the end of the url. If not, append '/'.
if (substr($url, -1)!=="/"){
$url .= "/";
}
//Return the processed url.
return $url;
}
//If the form was submitted
if(isset($_GET['siteurl'])){
//Put every new line as a new entry in the array
$urls = explode("\n",trim($_GET["siteurl"]));
//Iterate through urls
foreach ($urls as $url) {
//Parse the url to add 'http://' at the beginning or '/' at the end if not already there, to avoid errors with the get_meta_tags function
$url = parseUrl($url);
//Get the meta data for each url
$tags = get_meta_tags($url);
//Check to see if the description tag was present and adjust output accordingly
echo (isset($tags['description']))?"<tr><td>Description($url)</td> <td>".$tags['description']:"Description($url)</td><td>No Meta Description</td></tr>.";
}
}
?>
</table>
Thanks very much!
First, remove the last dot . in the line :
echo (isset($tags['description']))?"<tr><td>Description($url)</td> <td>".$tags['description']:"Description($url)</td><td>No Meta Description</td></tr>.";
EDIT :
I haven't seen this but you have one more error in this line :
Replace ".$tags['description']:" by ".$tags['description'].":
multiple ways to do this; why don't you use simpler way to do this
$tags = NULL;
$tags = get_meta_tags($url);
if($tags)
echo "<tr><td>Description($url)</td><td>" .$tags['description']. "</td></tr>";
else
echo "<tr><td>Description($url)</td<td>No Meta Description</td></tr>";
or if you want to stick with your code try this, need to have staring and ending tags for both true and false;
echo (isset($tags['description'])) ? '<tr><td>Description($url)</td><td>' . $tags['description'] . '</td></tr>' : '<tr><td>Description($url)</td><td>No Meta Description</td></tr>';

Checking if a url has http:// at the beginning & inserting if not [duplicate]

This question already has answers here:
How to add http:// if it doesn't exist in the URL
(8 answers)
Closed 9 years ago.
I am currently editing a wordpress theme with custom field outputs.
I have successfully made all the edits and everything works as it should.
My problem is that if a url is submitted into the custom field, the echo is exactly what was in there, so if someone enters www.somesite.com the echo is just that and adds it to the end of the domain: www.mysite.com www.somesite.com .
I want to check to see if the supplied link has the http:// prefix at the beginning, if it has then do bothing, but if not echo out http:// before the url.
I hope i have explained my problem as good as i can.
$custom = get_post_meta($post->ID, 'custom_field', true);
<?php if ( get_post_meta($post->ID, 'custom_field', true) ) : ?>
<img src="<?php echo bloginfo('template_url');?>/lib/images/social/image.png"/>
<?php endif; ?>
parse_url() can help...
$parsed = parse_url($urlStr);
if (empty($parsed['scheme'])) {
$urlStr = 'http://' . ltrim($urlStr, '/');
}
You can check if http:// is at the beginning of the string using strpos().
$var = 'www.somesite.com';
if(strpos($var, 'http://') !== 0) {
return 'http://' . $var;
} else {
return $var;
}
This way, if it does not have http:// at the very beginning of the var, it will return http:// in front of it. Otherwise it will just return the $var itself.
echo (strncasecmp('http://', $url, 7) && strncasecmp('https://', $url, 8) ? 'http://' : '') . $url;
Remember, that strncmp() returns 0, when the first n letters are equal, which evaluates to false here. That may be a little bit confusing.

php how to scan full page for all POST variables and then echo at top of page?

I can't echo my variable above my CMS include code.. but if I echo the variable after, then it recognizes the $url variable.
Here is some code:
<?php
// here is my CMS inlcude code
$template = 'news_script';
$number = '';
$category = '';
include $cutepath.'/show_news.php';
?>
If I echo $url above the include code, it returns nothing. But below, it obviously recognizes it.
Is there a php function that scans the whole page and retrieves all the POST variables so you can use $url at the top of the php page with a header('Location:'. $url); script??
Obviously $url is being defined in your show_news.php script. PHP executes a script line-by-line, and will not magically "reach back" to set a variables value in an earlier line.
Another (ugly) way would be:
<?php
// here is my CMS inlcude code
$template = 'news_script';
$number = '';
$category = '';
ob_start();
include $cutepath.'/show_news.php';
$buffered_data=ob_get_contents();
ob_end_clean();
echo $url; // here you could place your: header('Location:'. $url);
echo $buffered_data;
?>

Categories