I am new to php and trying to trim the lines of text generated by the ('information') part of the code seen below (in my custom WP theme):
<div class="information"><?php echo get_post_meta(get_the_ID(),'information',true); ?></div>
Each post has a different lenght of it's information (basically like a excerpt, but pulled from a custom field in each post) text, which messes up my archive/blog page, as i use a 3 columns grid. I need the lenght of all posts seen on the archive page to be equally long, by restricting the "information" text to be no more than lets say 150 characters long.
I see the fenction in this piece of code for example, taken from a default WP file, but can't seem to wrap it around my own piece of code seen above, to make it work like i want it to:
<?php
et_divi_post_meta();
if ( 'on' !== et_get_option( 'divi_blog_style', 'false' ) || ( is_search() && ( 'on' === get_post_meta( get_the_ID(), '_et_pb_use_builder', true ) ) ) ) {
truncate_post( 270 );
} else {
the_content();
}
?>
This is what i want/talk about:
Before:
POST 1
I am a wordpress post, with a long text, that should not be so long, as it makes the 3 column setup of the archive page look stupid.
After:
POST 1
I am a wordpress post, with a long text, that should not be so long...
How do i do this?
Thanks!
You can use substr() php function to get part of the string.
Take a look at this example function.
function trimResult($string, $len = 150){
if(strlen($string)> $len){
$string = substr($string,0,$len) . "..."; // to let the user know that was truncated...
}
return $string;
}
ref: http://php.net/substr
Specific code example, will be a better solution to include the php function on a global file.
<?php
function trimResult($string, $len = 150){
if(strlen($string)> $len){
$string = substr($string,0,$len) . "..."; // to let the user know that was truncated...
}
return $string;
}
?>
<div class="information"><?php echo trimResult(get_post_meta(get_the_ID(),'information',true)); ?></div>
Hope it helps.
$post = "I am a wordpress post, with a long text, that should not be so long, as it makes the 3 column setup of the archive page look stupid.";
$post = mb_strimwidth($post, 0, 70, "...");
echo $post;
result: "I am a wordpress post, with a long text, that should not be so long..."
Add ... if string is too long PHP
Related
I want to display a custom field we have [using the Estatik wordpress real estate plugin] if the database field has a value and hide that if it is empty. I can get the field to display and hide if empty or filled out, but, I cannot display the text: "Year built" when the year is filled out:
<?php if( es_the_property_field('year-built1594411179f5f08c8ab6ff14') ): ?>
<p>Year built: <?php es_the_property_field('year-built1594411179f5f08c8ab6ff14'); ?></p>
<?php endif; ?>
What can i change the code above to achieve:
If the year is filled out, I'd like it to display:
Year built: 1994
If the year is left empty, i'd like the paragraph to not print at all
thanks in advance!
For most data in WordPress, there are the_[…]() and get_the_[…]() style functions. Generally the the_ functions will output the data, and the get_the_ functions will return. Most plugins and themes have similar functionality. I downloaded the demo Estatik plugin and noticed that it does have that functionality as well.
In your if statement, you're actually outputting the year field there, and it's not returning a truthy value, so it stops there (otherwise it would show 1994Year Built: 1994).
The returning function is es_get_the_property_field( $field, $post_id = 0 );
So, coupling that with a little bit of cleanup (utilizing the before/after arguments of es_the_property_field, you would end up with something like this:
<?php if( es_get_the_property_field('year-built1594411179f5f08c8ab6ff14') ){
es_the_property_field('year-built1594411179f5f08c8ab6ff14', '<p>Year built: ', '</p>' );
} ?>
HOWEVER:
Here's the whole markup for the es_the_property_field() function:
/**
* Render property field.
*
* #param $field
* #param string $before
* #param string $after
*/
function es_the_property_field( $field, $before = '', $after = '' ) {
$result = es_get_the_property_field( $field );
echo ! empty( $result ) ? $before . $result . $after : null;
}
This means you could actually drop your if statement altogether, because that function checks to see if it's empty for you. So you could simplify it even further to just:
<?php es_the_property_field( 'year-built1594411179f5f08c8ab6ff14', '<p>Year Built: ', '</p>' ); ?>
Note: I don't have any personal experience with this plugin, this is all just based on what I found in the estatik/functions.php file.
I am not familiar with the Estatik theme but I can tell you that you could test the content like this.
<?php
$year_built = es_property_field('year-built1594411179f5f08c8ab6ff14');
if( $year_built != "" || $year_built != false ): ?>
<p>Year built: <?php echo date("Y", strtotime ($year_built)); ?></p>
<?php endif; ?>
So the two things you were missing was a proper test in the if statement and then echoing out the year_built with the date format. Now this is assuming a few things.
that es_the_property_field echos instead of returning which would be a very wordpress thing to do
that removing the "the" from that function is the version of that function that returns instead of echos.
I have a shortcode that is supposed to return the title and content for multiple custom posts on a single page. It correctly displays the title for each post, but when it comes to displaying each post's content, it only displays the content from the first post. What am I doing wrong?
Figuring out how to get the content from within a shortcode has been tricky enough, so if anyone has any suggestions, I'd appreciate it!
My code is:
if($customposts->have_posts() ) : while ($customposts->have_posts() ) : $customposts->the_post();
$post= get_the_ID();
$foo = get_the_title();
$bar=do_shortcode($content);
echo "<h2>".$foo."</h2><p>".$bar."</p>";
endwhile; endif;
It doesn't look like you need to us do_shortcode. If title is working correctly, you should be able to assign get_the_content() to your $bar variable.
$bar = get_the_content();
Since you're looping through posts, store the html from each iteration of the loop, and then return all of the html at once (remember, you can't echo or print from a shortcode callback... well, you shouldn't, or you'll get some unexpected results):
$html = '';
if($customposts->have_posts() ) :
while ($customposts->have_posts() ) : $customposts->the_post();
$post= get_the_ID();
$foo = get_the_title();
$bar = get_the_content();
$html .= "<h2>$foo</h2><p>$bar</p>";
endwhile; endif;
return $html;
Also, be careful about using $post as your own variable, you will undoubtedly come into conflict with other scripts, including core.
I'm using this code in our WordPress theme template to show the previous post which appears to work: previous_post_link('%link', '%title', true);
However, the content of %title includes the entire title of each post, which is very long and messes up the theme formatting.
Is there a way to modify the output of %title to limit to 20 characters?
Try this:
function modify_title_previous_post_link($link) {
preg_match('~>\K[^<>]*(?=<)~', $link, $match);
$title=$match[0];
$title = substr($title,0,20);
$title.="...";
$link=preg_replace('/<a(.+?)>.+?<\/a>/i',"<a$1>$title</a>",$link);
return $link;
}
add_filter('previous_post_link','modify_title_previous_post_link');
I'm not that good with regex, so I used this answer for preg_match and this answer for preg_replace.
I'm not a fan of the preg_match method.
Is there a reason that you have to pass '%title' into previous_post_link? The Wordpress function just does a text replacement on it, it's not really a complex macro or anything.
I'd do something more like
$prev_title = $get_previous_post()->post_title;
if (strlen($prev_title) > 20)
$prev_title = substr($prev_title , 0, 20) . '...';
previous_post_link('%link', $prev_title, true);
(I'm new to PHP so I might have gotten some syntax wrong, but that's the basic idea)
I want to append a disclaimer paragraph to my single posts based on a tag, specifically my "affiliate" tag. I have tried a few codes I found online that show some text but cause my excerpt to be blank. I don't have as much PHP knowledge as I'd like, if someone could point me in the right direction to writing a function for this.
Wordpress has a function for this: https://codex.wordpress.org/Function_Reference/has_tag
This should work:
<?php if ( has_tag('affiliate') ) { ?>
<p>Disclaimer paragraph</p>
<?php } ?>
I got it to work with this code, it's appearing after my social share buttons.. but oh well.
`function affiliate_add_to_content( $content ) {
if( is_single() ) {
if (has_tag('affiliate')) {
$content .= 'The disclaimer here';
}
}
return $content;
}
add_filter('the_content', 'affiliate_add_to_content');`
I'm currently trying to create a site for TV shows and due to certain wordpress limitations this is becoming a challenge.
However I bypass that with the use of implementing custom meta fields in the functions.php file, now my problem is that I need it to actively create new fields when I submit information in the current field. For example custom metabox names are
(Episode Name="This is It") (Episode Number="1") (Season Number="5")
Instead of having to create all the boxes from the beginning I would like the use Javascript (jQuery) or any solution to automatically create a new set of these 3 boxes
(Episode Name="") (Episode Number="") (Season Number="")
so I can just enter the new information as they come. Thank you in advance for your help!
Note: I have invested too much time into wordpress to just switch to another cms, so that is not an option at this point in time.
from what I understand of your question, you are looking for a simple solution to automate the input process. I have a general idea of what it is you nee to achieve as I have had to do something similar on a brochure type of website.
I have tried answering your question using Jquery, but I find it to increase the amount of text input required when creating your post, there is unfortunately no completely automated method of doing it, but hopefully below would provide you with a solution.
first I found the following plugin: Types - Complete Solution for Custom Fields and Types here: http://wordpress.org/extend/plugins/types/
This allows you to create custom meta feilds when creating a new post/page. The custom feilds are brought added with a perfix of "wpcf-" and then the name of the field, e.g. "Episode Name" becomes "wpcf-episode-name" in the database.
The following is an edit of wordpress's get_meta function:
function get_specifications(){
if ( $keys = get_post_custom_keys() ) {
echo '<div class="entry_specifications">';
foreach ( (array) $keys as $key ) {
$keyt = trim($key);
if ( '_' == $keyt[0] )
continue;
$values = array_map('trim', get_post_custom_values($key));
$value = implode($values,', ');
//remove "wpcf-"
$key = str_replace('wpcf-','',$key);
//convert "-" to a space " "
$key = str_replace('-',' ',$key);
//check if it has a value, continue if it does, skip if it doesn't:
if ($value <> ''){
echo apply_filters('the_meta_key', "
<div class='meta_wrapper'>
<div class='meta_title'>$key</div>
<div class='meta_value'>$value</div>
</div>\n", $key, $value);
};
}
}
// echo '</div>'; comment out and remove the line below if you are not using floats in your css
echo '</div><div class="clear"></div>';
}
In my page.php (or your template-page.php) I have added the following code when/where I want the meta to be produced:
<?php
//check to see if there is meta data, as you only want the meta data on TV Program pages
$met_check = get_post_meta($post->ID, 'wpcf-features', true);
if ($met_check <> ''){
//if it has a value, spit out "About EpisodeName" ?>
<h2 class="post-title clear">About <?php echo $title ?></h2>
<?php //perform the function from functions.php and return results:
echo get_specifications();
}
?>
I've styled the result with the following CSS:
.meta_entry {
clear:both;
}
.meta_title {
float:left;
text-transform:capitalize;
width:200px;
}
.meta_value {
float:left;
width:480px;
}
Hope this helps mate!
There is a wonderful plugin for wordpress called Pods which might be a viable solution.
Try http://wordpress.org/extend/plugins/custom-field-template/