displaying html from php - php

this has to do with wordpress and php. i have a function that takes an array of names from json. for each name i loop through, it creates a div with the name and an image inside. this div is then attached to a post and displayed on the front end. the problem is the image doesn't display correctly due to a 404 error. when i looked at the image source, the path to the image looked like this:
<img src="\"http://localhost/card-store/wp-content/themes/card-store-theme/images/baseball/team2.jpg\"">
clearly the path is broken so the 404 makes sense. seems like php is trying to escape some quotes, so i tried removing this with the str_replace, and as a shot in the dark i also tried html_entity_decode. also tried an absolute path to my images but that did not work either. when i refresh the page, the images appear fine, so i think its something to do with it not compiling right away? if that is true, how can i get it to display correctly without refreshing the page?
function test_function() {
if ( isset($_POST) ) {
$nameData = $_POST['nameData'];
//Strip any double escapes then use json_decode to create an array.
$nameDecode = json_decode(str_replace('\\', '', $_POST['nameData']));
//loop through names array and create a container for each
$html_string = "";
foreach ($nameDecode as $keyIndex => $name) {
$html_string .= '<div class="team-container team-container--inline col col--md-2 col--lg-2 col--xl-2"><img src="'. get_template_directory_uri() .'/images/baseball/team' . $keyIndex . '.jpg"> <p>'.$name.' <p /></div>';
}
echo ( $html_string);
//$html_final = str_replace('\\', '', $html_string);
$html_final = html_entity_decode($html_string);
// update teams post
if($html_string != "") {
$my_post = array(
'ID' => 9,
'post_content' => $html_final,
);
// Update the post into the database
wp_update_post( $my_post );
} else {
echo 'html string is empty!';
}
}
die();
}

If you want to remove the slashes try this.
$str = "Is your name O\'reilly?";
// Outputs: Is your name O'reilly?
echo stripslashes($str);
$nameData = $_POST['nameData'];
$stringObject = json_decode(stripslashes($nameData));
For json encode
json_encode($html_string, JSON_UNESCAPED_SLASHES);

Related

String to URL but detect if url is image?

i'm trying to do something in PHP
I'm trying to get the link of an image -> store it to my DB, but I'd like the user to be able to store text before it, and after it, I've gotten my hands on a similar function for links, but the image part is missing.
As you can see the turnUrlIntoHyperlink does a regex check over the entire arg passed, turning the text that contains it to the url, so users can post something like
Hey check this cool site "https://stackoverflow.com" its dope!
And the entire argument posting to my database.
However i can't seem to get the same function working for the Convert Image, as it simply won't post and removed text before/after it before when i made the attempt.
How would i do this in a correct way, and can i combine these 2 functions in to 1 function?
function convertImg($string) {
return preg_replace('/((https?):\/\/(\S*)\.(jpg|gif|png)(\?(\S*))?(?=\s|$|\pP))/i', '<img src="$1" />', $string);
}
function turnUrlIntoHyperlink($string){
//The Regular Expression filter
$reg_exUrl = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";
// Check if there is a url in the text
if(preg_match_all($reg_exUrl, $string, $url)) {
// Loop through all matches
foreach($url[0] as $newLinks){
if(strstr( $newLinks, ":" ) === false){
$link = 'http://'.$newLinks;
}else{
$link = $newLinks;
}
// Create Search and Replace strings
$search = $newLinks;
$replace = ''.$link.'';
$string = str_replace($search, $replace, $string);
}
}
//Return result
return $string;
}
more explained in detail :
When i post a link like https://google.com/ I'd like it to be a href,
But if i post an image like https://image.shutterstock.com/image-photo/duck-on-white-background-260nw-1037486431.jpg , i'd like it to be a img src,
Currently, i'm storing it in my db and echoing it to a little debug panel,
Do you mean that you want to make an <img> inside <a> element?
Your turnUrlIntoHyperlink function have captured the url successfully, so we can just use explode to get string before and after the link.
$exploded = explode($link, $string);
$string_before = $exploded[0];
$string_after = $exploded[1];
Code example:
<?php
function turnUrlIntoHyperlink($string){
//The Regular Expression filter
$reg_exUrl = "/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))/";
// Check if there is a url in the text
if(preg_match_all($reg_exUrl, $string, $url)) {
// add http protocol if the url does not already contain it
$newLinks = $url[0][0];
if(strstr( $newLinks, ":" ) === false){
$link = 'http://'.$newLinks;
}else{
$link = $newLinks;
}
$exploded = explode($link, $string);
$string_before = $exploded[0];
$string_after = $exploded[1];
return $string_before.'<img src="'.$link.'">'.$string_after;
}
return $string;
}
echo turnUrlIntoHyperlink('Hey check this cool site https://stackoverflow.com/img/myimage.png its dope!');
Output:
Hey check this cool site <img src="https://stackoverflow.com/img/myimage.png"> its dope!
Edit: the question has been edited
Since an image URL is just another kind of link/URL, your logic should go like this pseudocode:
if link is image and link is url
print <img src=link> tag
else if link is url and link is not image
print <a href=link> tag
else
print link
So you can just write a new function to "merge" those two function:
function convertToImgOrHyperlink($string) {
$result = convertImg($string);
if($result != $string) return $result;
$result = turnUrlIntoHyperlink($string);
if($result != $string) return $result;
return $string;
}
echo convertToImgOrHyperlink('Hey check this cool site https://stackoverflow.com/img/myimage.png its dope!');
echo "\r\n\r\n";
echo convertToImgOrHyperlink('Hey check this cool site https://stackoverflow.com/ its dope!');
echo "\r\n\r\n";
Output:
Hey check this cool site <img src="https://stackoverflow.com/img/myimage.png" /> its dope!
Hey check this cool site https://stackoverflow.com/ its dope!
The basic idea is that since image url is also a link, such check must be done first. Then if it's effective (input and return is different), then do <img> convertion. Otherwise do <a> convertion.

How to change the image source inside Wordpress Posts when an image is expired

As mentioned in the title. I try to change the image source to a default image, if an image's expiration date is expired.
I used ACF and added a new date field to all media files.
I then created the following function:
function check_expiration_date($post) {
$url = get_the_post_thumbnail_url($post->ID);
$thumbnail_id = get_post_thumbnail_id( $post->ID );
$today = date('d/m/Y');
$expire = get_field('expiration_date', $thumbnail_id);
if( $expire < $today && $expire!="" )
{
$url = "default.jpg";
}
return $url;
}
Now this function works for images that I add sepcifically in template files
but this will not work for images that have been added via the editor on post pages.
I tried to to use various hooks to change the html markup first before attempting to get the meta information but none of those had any effect on the outcome. Here an example:
function change_image_markup($html, $id, $caption, $title, $align, $url) {
$html5 = "<section>";
$html5 .= "<figure id='post-$id media-$id' class='align-$align'>";
$html5 .= "<img src='$url' alt='$title' />";
if ($caption) {
$html5 .= "<figcaption>$caption</figcaption>";
}
$html5 .= "</figure>";
$html5 .= "<section>";
return $html5;
}
add_filter( 'image_send_to_editor', 'change_image_markup', 10, 9 );
Is there a specific hook that can alter the html markup of images?
I am using Wordpress 5.5.1
any hint or tip is appreciated.
As the question is a month old and I did not receive any answers, I figured I would answer my own question. There is a difference in the requirements though. Instead of changing the image to a default one, I removed the image completely. Both can be achieved though.
So there was no real hook that could me out, as those hooks only call the action when actually inserting the image.
In my case everytime the post is being loaded the images had to be checked if they are expired or not.
Instead of working with hooks I created my own function and call that function inside single.php
In the single.php usually there is something like echo post->post_content;
Instead I call my function and give the post content as a value.
add_post_based_on_expiration_date($post->post_content);
And my function looks something like this:
function add_post_based_on_expiration_date($post_content){
$search_pattern = '/<figure(.*)\/figure>/'; //<figure(.*)/figure> /wp-image-(\d+)/
preg_match_all( $search_pattern, $post_content, $embedded_images );
$embedded_images_count = count( $embedded_images[0] );
$new_content = $post_content;
if ( $embedded_images_count > 0 ) {
for ( $i=0; $i < $embedded_images_count ; $i++ ) {
$dom = new DOMDocument;
#$dom->loadHTML($embedded_images[0][$i]);
$image = $dom->getElementsByTagName('img');
$imageId = str_replace("wp-image-" , "" , $image[0]->getAttribute('class'));
if(check_expiration_date_get_by_id($imageId)){
$new_content = str_replace($embedded_images[0][$i],"",$new_content);
}
};
};
echo $new_content;
}
It looks a bit messy but it does it's job. What I do is using regex to look for the image mark up <figure..... and save it in an array. Afterwards by using the DOM class I get the class, which contains the media ID. Then I call my function which is an alteration of the one above in the question. The function just returns true or false depeding on the expiration date. If it is true I remove it from the content and at the end I return it.
Therefore if an image is expired the image markup gets completely removed.
The downside of this aside from the messy code is the processing time. Since it it always called when opening a post site.

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

Getting Broken link on frontend for image uploaded via Wysiwyg editor in a custom module !

M getting this :
<img alt="" }}="" es_3.jpg="" wysiwyg="" src="{{media url=">
In my form i added this code
$wysiwygConfig = Mage::getSingleton('cms/wysiwyg_config')->getConfig(
array('tab_id' => 'form_section')
);
$wysiwygConfig["files_browser_window_url"] = Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/cms_wysiwyg_images/index');
$wysiwygConfig["directives_url"] = Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/cms_wysiwyg/directive');
$wysiwygConfig["directives_url_quoted"] = Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/cms_wysiwyg/directive');
$wysiwygConfig["widget_window_url"] = Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/widget/index');
$wysiwygConfig["files_browser_window_width"] = (int) Mage::getConfig()->getNode('adminhtml/cms/browser/window_width');
$wysiwygConfig["files_browser_window_height"] = (int) Mage::getConfig()->getNode('adminhtml/cms/browser/window_height');
$plugins = $wysiwygConfig->getData("plugins");
$plugins[0]["options"]["url"] = Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/system_variable/wysiwygPlugin');
$plugins[0]["options"]["onclick"]["subject"] = "MagentovariablePlugin.loadChooser('".Mage::getSingleton('adminhtml/url')->getUrl('adminhtml/system_variable/wysiwygPlugin')."', '{{html_id}}');";
$plugins = $wysiwygConfig->setData("plugins",$plugins);
$fieldset->addField('longdescription', 'editor', array(
'name' => 'longdescription',
'label' => Mage::helper('press')->__('Description'),
'title' => Mage::helper('press')->__('Description'),
'style' => 'width:500px; height:300px;',
'config' => $wysiwygConfig,
));
I m still not clear about the above code but i copied it from somewhere,But i do know that it enables to browse for images files instead of writing custom url.
After that i just call it in frontend like this:
<?php echo $item["longdescription"]; ?>
I am getting the text , but not the image and for image i am getting the broken link mentioned at top.
Am i missing something ?? if yes then what ?
add this code :
<?php $_cmsHelper = Mage::helper('cms');?>
<?php $_process = $_cmsHelper->getBlockTemplateProcessor();?>
<?php echo $_process->filter($item["longdescription"]); ?>
It looks like you might be breaking on quotes somewhere, how are you passing in the image/url of the image? If you look right here: alt="" }}="" es_3.jpg="" you can see that you are passing in closing brackets somewhere, and are skipping the SRC entirely. Try VAR_EXPORTing the $item and show me what you have.
I had the same problem today. It turns out that Mage_Adminhtml_Cms_WysiwygController::directiveAction() tries to create an image according to a url. This function calls Varien_Image_Adapter_Gd2::open() which in turn tries to open the file. This is where it goes wrong:
The image adaptor tries to get information about the image, like image size and mime type. But... when your site is on a localhost or a vagrant box or something like that, the sever tries to getimagesize('http://www.domain.com/image.jpg') instead of getimagesize('/Users/john/sites/domain.com/image.jpg') (for example).
The fix for this is to override the directiveAction() in your own module to add another catch before throwing an exception:
public function directiveAction()
{
$directive = $this->getRequest()->getParam('___directive');
$directive = Mage::helper('core')->urlDecode($directive);
$url = Mage::getModel('core/email_template_filter')->filter($directive);
try {
$image = Varien_Image_Adapter::factory('GD2');
$image->open($url);
$image->display();
} catch (Exception $e) {
// Try to get an absolute path:
$path = Mage::getBaseDir().'/'.preg_replace('/http:\/\/(.*)\//Ui', '', $url);
$image = Varien_Image_Adapter::factory('GD2');
$image->open($path);
$image->display();
} catch (Exception $e) {
$image = Varien_Image_Adapter::factory('GD2');
$image->open(Mage::getSingleton('cms/wysiwyg_config')->getSkinImagePlaceholderUrl());
$image->display();
}
}
A nice little bonus: the broken links in your admin are now gone too! ;-)

Categories