A client of mine wants a "project of the month" feature on his Wordpress site. But with a archive page.
My idea was to create a custom post type and call it projects. In here the client can manage projects and make new ones.
With this piece of code i can take the content from the latest project post, and put that content on the main "project of the month" page, while all the past projects are on the archive page.
$latest_cpt = get_posts("post_type=projects&numberposts=1");
$my_postid = $latest_cpt[0]->ID; //This is page id or post id
$content_post = get_post($my_postid);
$content = $content_post->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
This works ... but not really.
The project pages are build using visual composer. And some of the elements have background colors or padding. Visual composer gives these elements unique classes like
.vc_custom_1516702624245
And adds the custom style tag when the page loads. Something like this
<style type="text/css" data-type="vc_shortcodes-custom-css">
.vc_custom_1516711125312 {
padding-top: 75px !important;
padding-bottom: 75px !important;
background-color: #f3f5f6 !important;
}
.vc_custom_1516702624245 {
background-color: #f3f5f6 !important;
}
.vc_custom_1516711013808 {
margin-top: -106px !important;
}
.vc_custom_1516702490896 {
padding-left: 50px !important;
}
.vc_custom_1516703325534 {
margin-top: -15px !important;
}
.vc_custom_1516702744160 {
background-position: center !important;
background-repeat: no-repeat !important;
background-size: cover !important;
}
.vc_custom_1516702987431 {
padding-right: 65px !important;
}
.vc_custom_1516709810401 {
border-radius: 3px !important;
}
</style>
The problem with my approach is that visual composer does not create the style tag for the post content that is being loaded.
So therefore a lot of minor styling details are lost.
Image: Page content on archive page (how it should look)
Image: Page content on "project of the month" page
TL:DR visual composer style not generating post_content
You can use part of the addShortcodesCustomCss function of Vc_base:
$shortcodes_custom_css = get_post_meta( $id, '_wpb_shortcodes_custom_css', true );
if ( ! empty( $shortcodes_custom_css ) ) {
$shortcodes_custom_css = strip_tags( $shortcodes_custom_css );
echo '<style type="text/css" data-type="vc_shortcodes-custom-css">';
echo $shortcodes_custom_css;
echo '</style>';
}
replacing $id with yours $my_postid and, if needed, the echo with $content .=
Heres a function combining what i've seen across various stack overflow topics.
If you are using WPBakery for a page builder and want to use the WP_JSON api to serve your content to the frontend such as Angular or React you need to do a few things.
Tell wordpress to render the WP Bakery shortodes into actual HTML
Tell wordpress to include the dynamically generated css classes in the API response.
To do this I simply did the following:
add_action( 'rest_api_init', function ()
{
register_rest_field(
'page',
'content',
array(
'get_callback' => 'compasshb_do_shortcodes',
'update_callback' => null,
'schema' => null,
)
);
});
function compasshb_do_shortcodes( $object, $field_name, $request )
{
WPBMap::addAllMappedShortcodes(); // This does all the work
global $post;
$post = get_post ($object['id']);
$output['rendered'] = apply_filters( 'the_content', $post->post_content );
$output['css'] = '';
$shortcodes_custom_css = get_post_meta( $object['id'], '_wpb_shortcodes_custom_css', true );
if ( ! empty( $shortcodes_custom_css ) ) {
$shortcodes_custom_css = strip_tags( $shortcodes_custom_css );
$output['css'] .= $shortcodes_custom_css;
}
return $output;
}
This basically returns the following:
"content": {
"rendered": "<div class=\"row\"><div class=\"col-sm-12\"><div class=\"vc_column-inner\"><div class=\"wpb_wrapper\">\n\t<div class=\"wpb_text_column wpb_content_element\" >\n\t\t<div class=\"wpb_wrapper\">\n\t\t\t<p>I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.</p>\n\n\t\t</div>\n\t</div>\n</div></div></div></div><div class=\"row\"><div class=\"col-sm-6\"><div class=\"vc_column-inner\"><div class=\"wpb_wrapper\">\n\t<div class=\"wpb_text_column wpb_content_element\" >\n\t\t<div class=\"wpb_wrapper\">\n\t\t\t<p>I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.</p>\n\n\t\t</div>\n\t</div>\n</div></div></div><div class=\"col-sm-6\"><div class=\"vc_column-inner\"><div class=\"wpb_wrapper\">\n\t<div class=\"wpb_text_column wpb_content_element\" >\n\t\t<div class=\"wpb_wrapper\">\n\t\t\t<p>I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.</p>\n\n\t\t</div>\n\t</div>\n</div></div></div></div><div class=\"row\"><div class=\"col-sm-4\"><div class=\"vc_column-inner\"><div class=\"wpb_wrapper\">\n\t<div class=\"wpb_text_column wpb_content_element\" >\n\t\t<div class=\"wpb_wrapper\">\n\t\t\t<p>I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.</p>\n\n\t\t</div>\n\t</div>\n</div></div></div><div class=\"col-sm-4 vc_col-has-fill\"><div class=\"vc_column-inner vc_custom_1631795792357\"><div class=\"wpb_wrapper\"><h2 style=\"text-align: left;font-family:Abril Fatface;font-weight:400;font-style:normal\" class=\"vc_custom_heading\" >This is custom heading element</h2>\n\t<div class=\"wpb_text_column wpb_content_element\" >\n\t\t<div class=\"wpb_wrapper\">\n\t\t\t<p>I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.</p>\n\n\t\t</div>\n\t</div>\n</div></div></div><div class=\"col-sm-4\"><div class=\"vc_column-inner\"><div class=\"wpb_wrapper\"></div></div></div></div><div class=\"row\"><div class=\"col-sm-12\"><div class=\"vc_column-inner\"><div class=\"wpb_wrapper\"><div style='color:#FF0000;' data-foo='something'></div></div></div></div></div>\n",
"css": ".vc_custom_1631795792357{background-color: #afafaf !important;}"
},
You can then use the html on your frontend for example using angular by creating a dynamic route that feeds the slug in as a parameter, then simply connect a resolver service to it to hit the api for that page, if it's found, render the page, if not redirect to a 404.
The css can then be added in on component load by appending to the head.
And hey presto, you get WpBakery powered Angular.
Also for SEO, you can use SSR and WP Yoast to control and append meta tags from the WP Admin.
Any questions or improvement suggestions let me know.
function usp_modify_post_type($post_type) {
return 'post,footer,header,page,product,'; // Edit post type as needed
}
add_filter('usp_post_type', 'usp_modify_post_type');
Related
I am getting errors when I tried to include image in dompdf. I am using version 1.2.1
I tried with base4 encoded image as well from one of the solutions mentioned in forums, that also not working.
<?php
namespace Dompdf;
require_once 'dompdf/autoload.inc.php';
$_dompdf_show_warnings = true;
$_dompdf_warnings = [];
$path="http://localhost/dompdf/assets/images/logo.png";
$data = file_get_contents($path);
$image = 'data:image/' . $type . ';base64,' . base64_encode($data);
$htmldata = '<!DOCTYPE html>
<html>
<head>
<title>Results</title>
<style>
body {
background-color: lightblue;
}
.container {
width: 90%;
max-width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<h1>test pdf</h1>
<img src="/assets/images/logo.png" alt="image">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer egestas elementum justo, eget maximus odio ultricies eu. Aenean faucibus varius massa, sit amet sagittis neque vulputate luctus.</p>
<img src="'.$image.'" alt="base64">
</div>
</body>
</html>';
$options = new Options();
$options->getChroot($_SERVER['DOCUMENT_ROOT']."/dompdf/");;
$options->setisRemoteEnabled(true);
$options->setIsHtml5ParserEnabled(true);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($htmldata);
$dompdf->render();
$dompdf->stream("",array("Attachment" => false));
exit(0);
?>
Getting these errors, first is when I include the image path and second for base64 encoded one. I tried to enable remote, added chroot path and tried several solutions found on internet. Nothing helped.
Permission denied on /assets/images/logo.png. The file could not be found under the paths specified by Options::chroot. /assets/images/logo.png
Unable to create temporary image in /var/folders/bc/tnbzrzvd1k370wftgbm5lnqh0000gn/T data:image/;base64,iVBORw0KGgoAAAANSUhEUgA
EDIT:
Tried with file_exists() from the same directory and it works.
Can anyone suggest a solution for this?
Hey i want to display some html/css depending on how many rows there are in database basically. Is there a way to do this without echo? Because i'm lost when i have to use many ' '. Here is code sample
<?php foreach ($result as $row) {
}?>
<div id="abox">
<div class="abox-top">
Order x
</div>
<div class="abox-panel">
<p>lorem ipsum</p>
</div>
<br>
<div class="abox-top">
lorem</div>
<div class="abox-panel">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ac convallis diam, vitae rhoncus enim. Proin eu turpis at ligula posuere condimentum nec eu massa. Donec porta tellus ante, non semper risus sagittis at. Pellentesque sollicitudin sodales fringilla. Ut efficitur urna eget arcu luctus lobortis. Proin ut tellus non lacus dapibus vehicula non sit amet ante. Ut nibh justo, posuere sit amet fringilla eget, aliquam mattis urna.</p>
</div>
There's nothing complicated about it:
Simple/ugly:
<?php while($row = fetch()) { ?>
<div>
<?php echo $row['somefield'] ?>
</div>
<? } ?>
Alternative:
<?php
while ($row = fetch()) {
echo <<<EOL
<div>
{$row['somefield']}
</div>
EOL;
}
and then of course there's any number of templating systems, which claim to separate logic from display, and then litter the display with their OWN logic system anyways.
you can simply use <?= short opening tag introduced in php 5.3 before PHP 5.4.0 came out you had to enable short_open_tag ini but after 5.4.0 tag
here is an example
<?php $var='hello, world'; ?>
<?=$var ?> // outputs world
hope it helps.
Templates engines makes your life a pie
Take Smarty for example, it's pretty good template library. What template engine does is fetch variables to pre defined templates.
Your code in simple php:
<?php
echo 'My name is '. $name. ', that's why I'm awesome <br>';
foreach ($data as $value) {
echo $value['name'].' is awesome to!';
}
?>
Code in smarty:
My name is {$name}, that's why I'm awesome <br>
{foreach $data as $value}
{$value} is awesome to!
{/foreach}
Template engines pros:
Templates are held in separate custom named files. (i.e users.tpl, registration.tpl etc)
Smarty Caches your views (templates).
Simple to use i.e {$views + ($viewsToday/$ratio)}.
A lot of helpers.
You can create custom plugins/functions.
Easy to use and debug.
Most importantly: It separates your php code from html!
Template engines cons:
Sometimes hard to grip the concept of working for beginner.
Don't know any more actually
When I dont want to use a template engine (I like Twig, btw), I do something like this:
1) Write a separate file with the html code and some custom tags where data should be presented:
file "row_template.html":
<div class="abox-top">{{ TOP }}</div>
<div class="abox-panel"><p>{{ PANEL }}</p></div>
2) And then, read that file and do the replacements in the loop:
$row_template = file_get_contents('row_template.html');
foreach ($result as $row) {
$replaces = array(
'{{ TOP }}' => $row['top'],
'{{ PANEL }}' => $row['panel']
);
print str_replace(
array_keys($replaces),
array_values($replaces),
$row_template
);
}
In addition, you can change the content of "row_template.html" without touching the php code.
Clean and nice to the eye!
I am programming on wordpress and I want to edit a php file. I want the text to be displayed with line breaks and not all in one line.
Here is my code(I want jonh in one line and travolta in another but it gets displayed in one):
<div class="slide">
<img class="animated fade_left" src='<?php echo esc_url(onepage_get_option('onepage_testimonial_2_image', ONEPAGE_DIR_URI . "assets/images/team2.jpg")); ?>' onmouseover="javascript: this.title = '';" title="">
<div class="bx-caption animated fade_right"><span><a class="arrow"></a><?php echo esc_attr(onepage_get_option('onepage_testimonial_2_content', __('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.','one-page'))); ?><a class="testimonial"><?php echo esc_attr(onepage_get_option('onepage_testimonial_2_name', __('john \n travolta','one-page'))); ?></a></span></div>
Any suggestions?
If you want the link / element with the class testimonial on a new line, I would use css as that keeps it flexible and makes it easy to change if you want to do it differently in the future.
So in your css file:
.testimonial {
display: block;
}
In general, I would try to keep presentational stuff out of the php code.
I create a simple backed area for my client to post new job openings and was wanting to give them the ability to format the text a little by adding line breaks in the job description text that will be visible on the front end.
The job openings are stored in a MySQL database.
Example of what I'm talking about:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis quam sollicitudin, bibendum enim a, vulputate turpis.
Nullam urna purus, varius eget purus quis, facilisis lacinia nibh. Ut in blandit erat.
I've would like the breaks to happen when my client hits enter / return on the keyboard.
Any help on this matter would be appreciated.
------------UPDATE------------
okay so after much trial and error I got it somewhat working.
I added this line in my upload / action code.
$description = nl2br(htmlspecialchars($_POST['description']));
Full upload code is:
<?php
include($_SERVER['DOCUMENT_ROOT'] . "/connections/dbconnect.php");
$date = mysql_real_escape_string($_POST["date"]);
$title = mysql_real_escape_string($_POST["title"]);
$description = mysql_real_escape_string($_POST["description"]);
$description = nl2br(htmlspecialchars($_POST['description']));
// Insert record into database by executing the following query:
$sql="INSERT INTO hire (title, description, date) "."VALUES('$title','$description','$date')";
$retval = mysql_query($sql);
echo "The position was added to employment page.<br />
<a href='employment.php'>Post another position.</a><br />";
?>
Then on my form I added this to the textarea, but I get an error.
FYI that is line 80 the error is refering to.
Position Details:<br />
<textarea name="description" rows="8"><?php echo str_replace("<br />","",$description); ?></textarea>
</div>
Here is what the error looks like.
Here is my results page code:
<?php
$images = mysql_query("SELECT * FROM hire ORDER BY ID DESC LIMIT 10");
while ($image=mysql_fetch_array($images))
{
?>
<li data-id="id-<?=$image["id"] ?>">
<div class="box white-bg">
<h2 class="red3-tx"><?=$image["title"] ?> <span class="date-posted blue2-tx"><?=$image["date"] ?></span></h2>
<div class="dotline"></div>
<article class="blue3-tx"><?=$image["description"] ?><br />
<br />
For more information please call ###-###-####.</article>
</div>
</li>
<?php
}
?>
If I delete all that error copy and write out a real position with line breaks it works.
I have no idea how to fix the error though.
Again any help would be appreciated.
Thanks!
you can use str_replace
$statement = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla quis quam sollicitudin, bibendum enim a, vulputate turpis.
Nullam urna purus, varius eget purus quis, facilisis lacinia nibh. Ut in blandit erat."
$statement = str_replace(chr(13),"<br/>", $statement);
query example : INSERT INTO table (statement) VALUES ('$statement');
hope this can help you
EDIT :
if you want display the result at textarea from database u can using this code
$des = $row['description'] //my assumption that your feild name at table inside mySQL is description
Position Details:<br />
<textarea name="description" rows="8"><?php echo str_replace("<br />",chr(13),$des); ?></textarea>
</div>
hope this edit can help your second problem
I would start by answering a couple of questions first
Do I want my database to store html-formatted user input?
Is the data going to be editable afterwards?
Since you seem to want only nl2br, a simple approach would be to save the content as is in the database, then use nl2br() on the output side as Marcin Orlowski suggested.
I am working with html document generated from Micrsoft Word 2007/2010. Besides generating incredibly dirty html, word also has the tendency of using both block and inline style. I am looking for a php library would merge block into already existing inline style element.
Edit
The goal is to construct a html block preserve the original formatting and editable in WYSIWYG editor like tinyMCE
Example
If the original html is:
<html>
<head>
<style>
.normaltext {color:black;font-weight:normal;font-size:10pt}
.important {color:red;font-weight:bold;font-size:11pt}
</style>
<body>
<p class="normaltext" style="font-family:arial">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
In ut erat id dui mollis faucibus. Mauris eu neque et eros tempus placerat.
<span class="important">Nam in purus nisi</span>, vitae dictum ligula.
Morbi mattis eros eget diam vulputate imperdiet.
<span class="important" style="color:green">Integer</span> a metus eros.
Sed iaculis porta imperdiet.
</p>
</body>
</html>
Should become:
<html>
<head>
<body>
<p style="font-family:arial;color:black;font-weight:normal;font-size:10pt">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
In ut erat id dui mollis faucibus. Mauris eu neque et eros tempus placerat.
<span style="color:red;font-weight:bold;font-size:11pt">Nam in purus nisi</span>, vitae dictum ligula.
Morbi mattis eros eget diam vulputate imperdiet.
<span style="color:green;font-weight:bold;font-size:11pt">Integer</span> a metus eros.
Sed iaculis porta imperdiet.
</p>
</body>
</html>
Check out:
http://inlinestyler.torchboxapps.com/
http://premailer.dialect.ca/
http://www.pelagodesign.com/sidecar/emogrifier/
http://blog.verkoyen.eu/blog/p/detail/convert-css-to-inline-styles-with-php
http://beaker.mailchimp.com/inline-css
http://burrowscode.wordpress.com/2011/02/19/emailify-internal-stylesheets-to-inline-styles/
https://github.com/crcn/emailify
https://github.com/peterbe/premailer
Porting code from either of the sources to PHP, or using any of the available APIs should do the trick of getting your CSS styling inline.
See the CssToInlineStyles project which does exactly what you want.
No, but try this instead, copying and pasting from word into http://ckeditor.com/ or tinymce, etc does clean it up A LOT, thought it's still not perfect it will get you much closer.
I finally managed to get it to work. The code is based off of
http://blog.verkoyen.eu/blog/p/detail/convert-css-to-inline-styles-with-php
with once simple change:
Moving the line
// add new properties into the list
foreach($rule['properties'] as $key => $value) $properties[$key] = $value;
up to the begining of the loop, right after where $properties is declared.
To make this work for WordPress however, one additional change is needed. DomDocument replace &nbps; from the document with blanks, which breaks WordPress update statement and lead to cotent being cut off. Please refer to my other question for the solution:
DOMDocument->saveHTML() converting to space
This problem is detailed in https://wordpress.stackexchange.com/questions/48692/post-content-getting-cut-off-on-blank-space-on-wpdb-update. If you know why this is happening for WordPress, please post your answer there as I would very much like to find out why it is happening.