MPDF Wordpress pull in variables - php

I am using MPDF with Wordpress and ACF to create vouchers. I want to click a button on my custom post type to generate the pdf (this works). I then want to pull variables into the PDF to fill it with dynamic content from my custom post type and advanced custom fields, it doesn't show errors the values are just blank. This is my code so far:
Button on post:
<a href="<?php get_bloginfo('url'); ?>?offer=<?php echo $post->ID ?>" download>Download The Voucher</a>
Functions.php code to generate the pdf:
add_action('init', 'congres_redirect');
function congres_redirect() {
if(isset($_GET['offer'])) {
$restName = get_field('restaurant_name', $post->ID);
$image = get_field('restaurant_image', $post->ID);
view_conferinta();
}
}
function view_conferinta() {
$output = '<html>
<head><title>Voucher Download</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head>
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Open+Sans" />
<style>
.voucher-content {
padding: 20px;
}
.inner-voucher {
padding: 20px;
border: solid 1px #000;
}
</style>
<body>';
$output .= '
<div class="voucher-content" style="font-family:chelvetica">
<div class="inner-voucher">
<img src=".$image." alt="Logo" style=" margin: 0;" />
<h1>Voucher Title</h1>
<p>Voucher Description</p>
<p>Voucher Code: EL-200DEG07022020-123AB</p>
<p>Restaurant Name:'.$restName.'</p>
<p>This is my static voucher template</p>
<p>POST ID:'.$post->ID.'</p>
</div>
</div>
';
$output .= '
</body>
</html>';
require_once __DIR__ . '/mpdf/vendor/autoload.php';
$mpdf = new \Mpdf\Mpdf(['debug' => true]);
$mpdf->WriteHTML($output);
$mpdf->Output('my-voucher.pdf','I');
//$mpdf->Output($pdfheader.'.pdf', 'D');
exit;
}
This generates a pdf but all the dynamic content is blank. What am I doing wrong?

You're not passing the dynamic variables into the function creating the output. You also need to declare the $post global
Change
function view_conferinta() {
$output = '<html>
to
function view_conferinta(restName, $image) {
global $post;
$output = '<html>
Then add global post to your init function:
function congres_redirect() {
if(isset($_GET['offer'])) {
global $post; //ADD THIS
$restName = get_field('restaurant_name', $post->ID);
$image = get_field('restaurant_image', $post->ID);
view_conferinta();
}
}

Related

Insert custom field to custom post type

I have a component made by a plugin which displays a list of articles from a custom post type. Each article has the class post-id associated with. I can't override plugin's files in child theme to loop inside the template that generates the list so I need to create a function in functions.php. What I need is to replace a div inside the article with a new div styled with a custom field ( color picker ) made with advanced custom field plugin, that is associated to each article dynamically.
loop {
display: flex;
width: 100%;
}
article {
width: 200px;
height: 200px;
background: red;
margin:20px;
display:flex;
justify-content:center;
align-items:center;
}
.overlay {
width:150px;
height:150px;
}
<article class="portfolio-item post-53">
<div class="overlay" style="background-color:#000"></div>
</article>
<article class="portfolio-item post-65">
<div class="overlay" style="background-color:#000"></div>
</article>
<article class="portfolio-item post-70">
<div class="overlay" style="background-color:#000"></div>
</article>
function insert_custom_div() {
$args = array(
'meta_key' => 'new_color',
'post_type' => 'portfolio-item'
);
$posts = get_posts($args);
foreach ($posts as $post):
$color_picker_custom_field = get_field('new_color', $post->ID);
if ($color_picker_custom_field) {
?>
<script>
jQuery( document ).ready( function() {
jQuery('article').append('<div class="overlay post-<?php echo $post->ID; ?>" style="background-color:<?php echo $color_picker_custom_field; ?>"></div>');
});
</script>
<?php
}
endforeach;
}
add_action('wp_head','insert_custom_div');
You can get new color from each post to array and then pass the array to javascript with json_encode()
Here is modified fragment of your code, I'm not sure it will work since html injections to functions.php is bad practice, it's better to do it in template. Well it's just direction for thoughts:
<?php
$new_div = array();
foreach ($posts as $post):
$color_picker_custom_field = get_field('new_color', $post->ID);
$new_div[] = '<div class="overlay" style="background-color:<?php echo $color_picker_custom_field; ?>"></div>';
endforeach;
?>
<script>
jQuery( document ).ready( function() {
var new_divs = <?php echo json_encode($new_div); ?>;
jQuery( '.overlay' ).each( function(ind, el) {
jQuery(this).replaceWith(new_divs[ind]');
});
});
</script>

How to put the HTML output with overlay inside the OwlCarousel

I have a slider in my page and every slider has it's own overlay descriptions and this descriptions are in the HTML format.
In my admin module there is a setting there that the user can create their own slider images with custom message using CKEditor.
And my problem is when I try to display the descriptions in the slider it's just plain HTML code.
Here's a bit of my code:
Controller Part
foreach($results as $result) {
if ($result['banner_image'] && file_exists(DIR_IMAGE . $result['banner_image'])) {
$image = $this->model_tool_image->resize($result['banner_image'], 40, 40);
$banner_image_large = HTTP_IMAGE . $result['banner_image'];
} else {
$image = $this->model_tool_image->resize('no_image.jpg', 40, 40);
}
$url = '&banner_id=' . (int)$result['banner_id'];
$this->data['banners'][] = array(
'banner_id' => $result['banner_id'],
'banner_image' => $image,
'banner_image_large' => $banner_image_large, // here's the image to be use in the slider
'code_description' => $result['banner_description'], //here's the raw HTML formatted description
'description' => strip_tags(html_entity_decode($result['banner_description'])),
'banner_link' => $result['banner_link'],
'action' => $this->url->link('project/banner_slider/update', 'token=' . $this->session->data['token'] . $url, 'SSL')
);
}
In my View
<h1>Carousel Demo</h1>
<div id="owl-demo" class="owl-carousel owl-theme">
<?php foreach($banners as $banner) { ?>
<div class="item">
<div class="textoverlay"><?php echo $banner['code_description']; ?></div> <!-- overlay the decription -->
<img src="<?php echo $banner['banner_image_large']; ?>" />
</div>
<?php } ?>
</div>
Here's some CSS
#owl-demo .item img{
display: block;
width: 100%;
height: auto;
}
.textoverlay{
position: absolute;
display:block;
}
And JS:
$('#owl-demo').owlCarousel({
autoPlay : 3000,
stopOnHover : true,
navigation : false, // Show next and prev buttons
slideSpeed : 300,
paginationSpeed : 400,
singleItem:true,
autoHeight : true,
transitionStyle:"fade"
});
surround the raw html with $.parseHTML("your html here");
Ok I solved it by using html_entity_decode() function

Wordpress unique background in posts that are in specific category

i have a code:
<body <?php if( in_category( 11446 ) ) { echo "style=\"background-image: url('my-background-url-of-image');background-repeat:repeat;\" onclick=\"window.open('http://www.domain.com');\""; } ?> >
This code works only until page loads fully than something happens and it doesn't work i assume from inspect element that onclick function changes and i'm failing to find what part tricks that.
What this code does is it sets unique body background that are in specific category and background is clickable.
But because of some javascript error it doesn't work when page loads full so maybe somebody could explain me how to remove attr on Javascript and than add my with domain i want. Or maybe give example how to do alternative code just with href.
Thank you.
I'm assuming you are building a Wordpress template and the background image to be used is based upon the category of a Wordpress post.
This uses no Javascript. Instead, what it does is create the CSS declaration block inside the head tag of the HTML5 document on the fly. It does no inline CSS for the body tag.
<?php
// ====================================================
// Solution #1
// Background Image Only
// ====================================================
function GetThisWordpressPostCategory() {
// Do post category to filename mapping here
return("cars");
}
function in_category() {
// Just a dummy to simulate Wordpress in_category call
return(true);
}
function BodyBackground($category) {
$bodyCss = "";
if (in_category($category)) {
$bodyCss =<<<CSS
<style type="text/css">
body {
background-image: url('{$category}.jpg');
}
</style>
CSS;
}
return($bodyCss);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Category background</title>
<?php
$category = GetThisWordpressPostCategory();
echo BodyBackground($category);
?>
</head>
<body>
</body>
</html>
<?php
// ====================================================
// Solution: 2
// Clickable div spanning viewport
// ====================================================
function GetThisWordpressPostCategory() {
// Do post category to filename mapping here
return("cars");
}
function in_category() {
// Just a dummy to simulate Wordpress in_category call
return(true);
}
function PageCss($category) {
$pageCss = "";
if (in_category($category)) {
$pageCss =<<<CSS
<style type="text/css">
html, body, #page {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-image: url('{$category}.jpg');
}
#page-anchor {
display: block;
width: 100%;
height: 100%;
}
</style>
CSS;
}
return($pageCss);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Category background</title>
<?php echo PageCss(GetThisWordpressPostCategory()); ?>
</head>
<body>
<div id="page">
<a id="page-anchor" href="http://www.google.com"></a>
</div>
</body>
</html>

How to pass dynamic variable through class function

I'm trying to pass every value through the function (it's a part of cms) so later on user can view content and then when he confirms it is saved to database and a separate file is made that looks exactly as preview but I don't know and have no idea how to pass a dynamic variable like $_POST['champno'.$i] right below
public function display($patch, $champ_number){
echo '<h1 style="float: left;">PATCH ';
echo $patch.'</h1>
<nav id="header-menu">
<ul>
<li>PATCHES</li>
<li>CHAMPIONS</li>
<li>ITEMS</li>
<li>CHANGES</li>
</ul>
</nav>
<div id="title">
<h2>CHAMPION BALANCE CHANGES</h2>
</div>';
for($i=1;$i<=$champ_number; $i++){
?>
<style type="text/css" scoped>
#media(min-width: 640px){
.<?php echo $_POST['champno'.$i]; ?>{
background-image: url('../../assets/champions/<?php echo $_POST['champno'.$i]; ?>_pc.jpg');
Extract the information from $_POST['champno'.$i] into a dedicated array and call the function with that:
$champions = array();
for ($i = 1; $i <= $champ_number; $i++)
$champions[] = $_POST['champno' . $i];
$obj->display($patch, $champions);
In the function:
function display($patch, $champions) {
...
foreach ($champions as $champion) {
$champion = htmlspecialchars($champion);
?>
<style type="text/css" scoped>
#media(min-width: 640px) {
.<?php echo $champion; ?> {
background-image: url('../../assets/champions/<?php echo $champion; ?>_pc.jpg');
...
<?php
}
}
Then you can use the function with the database and all other input sources.

Cykod FlashWavRecorder PHP save - upload to server problem

I believe I have most everything correctly configured for the recorder because I can
1 - Get the Flash permission prompt
2 - Start recording
3 - Listen to the playback
but when I go to save the file I can find it neither in the upload directory nor the temp dir.
I know php is working because I have tested a post - upload form successfully.
Here's the html and php:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>My Recorder</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js'></script>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/recorder.js"></script>
<script type="text/javascript">
$(function() {
var appWidth = 24;
var appHeight = 24;
var flashvars = {'event_handler': 'microphone_recorder_events', 'upload_image': 'images/upload.png'};
var params = {};
var attributes = {'id': "recorderApp", 'name': "recorderApp"};
swfobject.embedSWF("recorder.swf", "flashcontent", appWidth, appHeight, "10.1.0", "", flashvars, params, attributes);
});
</script>
<style>
#control_panel { white-space: nowrap; }
#control_panel a { outline: none; display: inline-block; width: 24px; height: 24px; }
#control_panel a img { border: 0; }
#save_button { position: absolute; padding: 0; margin: 0; }
#play_button { display: inline-block; }
</style>
</head>
<body>
<div id="status">
Recorder Status...
</div>
<div id="control_panel">
<a id="record_button" onclick="Recorder.record('audio', 'audio.wav');" href="javascript:void(0);" title="Record"><img src="images/record.png" width="24" height="24" alt="Record"/></a>
<span id="save_button">
<span id="flashcontent">
<p>JavaScript enabled and Adobe Flash Player installed, please</p>
</span>
</span>
<a id="play_button" style="display:none;" onclick="Recorder.playBack('audio');" href="javascript:void(0);" title="Play"><img src="images/play.png" width="24" height="24" alt="Play"/></a>
</div>
<div id="upload_status">
</div>
<form id="uploadForm" name="uploadForm">
<input name="authenticity_token" value="xxxxx" type="hidden">
<input name="upload_file[parent_id]" value="1" type="hidden">
<input name="format" value="json" type="hidden">
</form>
</body>
</html>
<?php
$save_folder = dirname(__FILE__) . "/audio";
if(! file_exists($save_folder)) {
if(! mkdir($save_folder)) {
die("failed to create save folder $save_folder");
}
}
function valid_wav_file($file) {
$handle = fopen($file, 'r');
$header = fread($handle, 4);
list($chunk_size) = array_values(unpack('V', fread($handle, 4)));
$format = fread($handle, 4);
fclose($handle);
return $header == 'RIFF' && $format == 'WAVE' && $chunk_size == (filesize($file) - 8);
}
$key = 'filename';
$tmp_name = $_FILES["upload_file"]["tmp_name"][$key];
$upload_name = $_FILES["upload_file"]["name"][$key];
$type = $_FILES["upload_file"]["type"][$key];
$filename = "$save_folder/$upload_name";
$saved = 0;
if($type == 'audio/x-wav' && preg_match('/^[a-zA-Z0-9_\-]+\.wav$/', $upload_name) && valid_wav_file($tmp_name)) {
$saved = move_uploaded_file($tmp_name, $filename) ? 1 : 0;
}
if($_POST['format'] == 'json') {
header('Content-type: application/json');
print "{\"saved\":$saved}";
} else {
print $saved ? "Saved" : 'Not saved';
}
exit;
?>
btw - this came straight from the cykod site, I've done barely anything to it...
also, how do i convert to mp3 upon pressing the save button?
Thanks!
Don't know if you ever got an answer to this, but check your folder permissions. After setting my "audio" folder such that everyone can read/write it worked. Of course this is not the best way to do this - you need to set your apache/php account to be writeable to the folder - but at least this should get you going.

Categories