I'm trying to get the_title(); from a wordpress page to use it in a php script
my code:
<?php
global $post;
$args = array( 'numberposts' => 10, 'category_name' => 'bin-o' );
$posts = get_posts( $args );
foreach( $posts as $post ): setup_postdata($post); ?>
$project_name = the_title();
$post_id = get_page_id('$project_name');
var_dump($project_name);
?>
<a href="<?php echo get_site_url() . '/?p=' . $post_id ?>"><h1><?php the_title() ?></h1>
<?php the_content() ?></a>
The functions.php:
<?php
// Get the id of a page by its name
function get_page_id($page_name){
global $wpdb;
$page_name = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_name = '".$page_name."'");
return $page_name;
}
?>
The problem is it only gives the_title() When it is printed.
so I can't use the_title() to use it for a php script cause the_title will return NULL
how can I fix this so I can use the requested title to use this further in the php script
You use get_the_title().
Many wordpress in-loop functions have corresponding get_ versions, which will return the value, instead of echoing it.
I've used this now:
<?php
$project_name = trim(ucfirst(get_the_title())); //The title of current post!
$project_info = get_page_by_title($project_name);
$project_id = $project_info->ID;
?>
<a href="<?php echo get_site_url() . '/?p=' . $project_id ?>"><h1><?php the_title() ?></h1>
<?php the_content() ?></a>
The project_info get's all the project info, project_id gets the ID out of the project info and uses that to redirect to the wanted page. so I dont have to use the functions anymore
Related
here is my scenario: I got an index.php which loads every page I got one below the other. It's a one-pager in the end.
I found this snippet online and It helped me a lot by creating this.
<?php
$mypages = get_pages( array('child_of' => 1503, 'sort_column' => 'menu_order') );
foreach( $mypages as $page ) {
$content = $page->post_content;
if ( ! $content ) // Check for empty page
continue;
$content = apply_filters( 'the_content', $content );
?>
<section>
<div class="headlines info-header"><img src="<?php echo get_template_directory_uri(); ?>/assets/images/arrow.png" alt="arrow"><?php echo $page->post_title; ?></div>
<div class="page-content"><?php echo $content; ?></div>
</section>
<?php
}
?>
It seems to work just fine. But now to the problem part of this. I want to display the posts also on this one page. My try was to create another page news and place a widget on this page which shows the latests posts, filtered by category.
But now the page title won't show up anymore, all I got is the following
notice: NOTICE: TRYING TO GET PROPERTY 'POST_TITLE' OF NON-OBJECT IN
So I thought the problem might have to do with the little <?php echo $page->post_title; ?> I already tried to just get the_titlebut I ended up getting the same error.
I'm kinda new to Wordpress so I don't know how to deal with this.
Is there another way to get the page title on my index.php?
Best,
Dominik
I managed to fix this. As #delboy1978uk told me, I check if the title is not empty by adding 2 lines of code.
Here is the final code:
<?php
$mypages = get_pages( array('child_of' => 1503, 'sort_column' => 'menu_order') );
foreach( $mypages as $page ) {
$content = $page->post_content;
$title = $page->post_title;
if ( ! $content ) // Check for empty page
if ( ! $title) // Check for empty title < NEW!
continue;
$content = apply_filters( 'the_content', $content );
?>
<section>
<div class="headlines info-header"><img src="<?php echo get_template_directory_uri(); ?>/assets/images/arrow.png" alt="arrow"><?php echo $title; ?></div>
<div class="page-content"><?php echo $content; ?></div>
</section>
<?php
}
?>
This is a music website with multiple artist pages - one page per artist. New content is added as a post with a Wordpress tag to denote the artist. This is so that I can add a Wordpress loop on each artist page to show all the posts filtered with that artist's tag.
I've got the filtered loop working correctly, but unfortunately it's currently hardwritten inside the page template's HTML, so it's only filtering for one tag. I don't want to create a new page template for each artist, so I'd like to add it to my functions.php file instead, where I can instead create a new shortcode for each artist.
Here's the current code in my page template, which filters the loop for all posts with our seefour tag:
<?php
query_posts( "tag=seefour" );
if ( have_posts() ) { ?>
<?php while ( have_posts() ) { ?>
<?php the_post(); { ?>
<div class="jd-box">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( ); ?>
<div class="jd-overlay"></div>
<div class="jd-overlay-text">
<?php the_title(); ?>
</div>
</a>
</div>
<?php } ?>
<?php } ?>
<?php } ?>
I'm assuming the best option is to turn this into a seefour shortcode inside my functions.php file - how can I achieve this?
Bonus question: is this sustainable in the long run (with 30-50+ artists) or will it cause a lot of redundant code? Open to suggestions...
P.S. I know this kind of question has been answered already (starting with raw PHP), but since I'm starting with a mix of HTML/PHP (and I'm a PHP newb), I just can't get it to work. So my apologies for asking again.
First of all, you should never ever use query_posts(). It is internal WordPress function to create and maintain the main WordPress cycle. Using it, you can crash your site in unpredictable manner. You should use get_posts() or WP_Query instead.
To have your custom shortcode, add the following to your functions.php:
function showtag_shortcode( $atts ) {
$atts = shortcode_atts( array(
'tag' => '', // Default value.
), $atts );
$posts = get_posts( 'tag=' . $atts['tag'] );
if ( $posts ) {
$output = '';
foreach ( $posts as $post ) {
setup_postdata( $post );
$output .= '<div class="jd-box">';
$output .= '<a href="' . get_the_permalink( $post ) . '">';
$output .= get_the_post_thumbnail( $post );
$output .= '<div class="jd-overlay"></div>';
$output .= '<div class="jd-overlay-text">';
$output .= get_the_title( $post );
$output .= '</div>';
$output .= '</a>';
$output .= '</div>';
}
} else {
$output = 'no data';
}
wp_reset_postdata();
return $output;
}
add_shortcode( 'showtag', 'showtag_shortcode' );
This function created [showtag] shortcode with one parameter: tag. You can use this shortcode on any page as follows:
[showtag tag="seefour"]
[showtag tag="disco"]
etc. You will have posts with relevant tags to be shown in place of your shortcode.
Putting a whole loop in a shortcode will make it messy, I know you can use shortcodes in Widgets etc as well but I guess that's not what you're after.
If so, the best option would be to make this code a page template say Artist and pass a variable in URL i.e. http://example.com/artist?t=seefour and then use the following code in the page template.
<?php
/**
* Template Name: Artist
*/
query_posts( "tag=" . $_GET['t'] );
if ( have_posts() ) {
?>
<?php while ( have_posts() ) { ?>
<?php the_post(); { ?>
<div class="jd-box">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( ); ?>
<div class="jd-overlay"></div>
<div class="jd-overlay-text">
<?php the_title(); ?>
</div>
</a>
</div>
<?php
}
}
}
?>
This can be used for any number of artists, totally flexible because it is dependant on a variable that is provided on run time (when accessed).
Trying to write my first short-code that displays all post-titles in a specific Category. But it is not displaying the actual results, just the short code.
Here is what I have so far in my child theme's functions.php file:
function posts_in_cat() {
echo '<ul>';
query_posts('cat=3'); while (have_posts()) : the_post();
echo ('<li>' . the_title() . '</li>');
endwhile;
wp_reset_query();
echo '</ul>';
}
add_shortcode( 'display_posts_in_cat', 'posts_in_cat' );
And then I am calling the short code, like so [display_posts_in_cat].
Any help would be greatly appreciated as I try and learn this.
EDIT: I have gotten it to display but the link itself is being echo-ed in front of the title in text. Also, it is not displaying more than 10 of the titles and I want it to display them all. Any ideas...?? Thanks.
First and foremost, avoid using query_posts() – it's inefficient. Check out this SO answer for the skinny.
Additionally, shortcodes shouldn't make use of echo statements. Shortcodes only return text. Put simply, WordPress has PHP internally that says "when this specific shortcode is entered into the editor, replace it with the text returned from this function." Using echo causes you to immediately print those statements to the screen, rather than returning to WordPress so that it can continue with its regular process. More on the WP Codex.
And, finally, shortcode functions require $atts as a parameter.
So, with all that said, here's how I would rewrite your function:
<?php
function posts_in_cat( $atts ) {
$atts = shortcode_atts( array(
'cat' => '',
), $atts );
if ( empty( $atts['cat'] ) ) {
// If category provided, exit early
return;
}
$args = array(
'category' => $atts['cat'],
// Disable pagination
'posts_per_page' => -1
);
$posts_list = get_posts( $args );
if ( empty( $posts_list) ) {
// If no posts, exit early
return;
}
$opening_tag = '<ul>';
$closing_tag = '</ul>';
$post_content = '';
foreach ( $posts_list as $post_cat ) {
$post_content .= '<li>' . esc_html( get_the_title( $post_cat->ID ) ) . '</li>';
}
return $opening_tag . $post_content . $closing_tag;
}
add_shortcode( 'display_posts_in_cat', 'posts_in_cat' );
I'm just adding all of the content you were echoing into a handful of variables, and then returning them, concatenated, at the end. Also, I added in an if statement to exit early if there aren't any posts in the category. That way you don't have an empty <ul> element cluttering up the page.
I've also escaped the outputs, which you can read about on the Codex.
Please try this:
function posts_in_cat() { ?>
<ul class="posts">
<?php query_posts('cat=3&showposts=50'); while (have_posts()) : the_post();
?>
<li><a href='<?php the_permalink() ?>'><?php the_title(); ?></a></li>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</ul>
<?php
}
add_shortcode( 'display_posts_in_cat', 'posts_in_cat' );
i built a short-code in wordpress to show related posts in the sidebar. Please look on the right at this website: http://www.immvestwolf.de/news/
But i get a php error (Notice: Undefined variable: count in /web/1/000/045/787/175759/htdocs/immvestwolf/wp-content/themes/le-quartier/functions.php on line 74)
i dont knwo whats wrong with this code. On other sites the code works without an php error.
Here is my php code :
function my_recent_posts_with_image() {
// Lese die letzten zehn publizierten Artikel aus
$args = array(
'posts_per_page' => 10
);
$recent_posts = get_posts( $args );
echo '<div class="widget recent_posts_with_image_by_jongo">';
echo '<h5 class="widget_title">Die 10 letzten News</h5>';
foreach ( $recent_posts as $post ) {
$count++;
?>
<div>
<a title="Veröffentlich am: <?php echo get_the_time('d.m.Y', $post->ID ) ?>" href="<?php echo get_permalink( $post->ID ); ?>"><?php echo get_the_post_thumbnail( $post->ID, array(70,50) ); ?><p><?php echo get_the_title( $post->ID ); ?></p>
</a>
</div>
<?php
}
echo '</div>';
}
add_shortcode('get_recent_posts_with_image','my_recent_posts_with_image');
The error is at the line $count++;
Any ideas to correct this?
$count is never defined...It's up to you to define it. For example:
$count = 0;
foreach ( $recent_posts as $post ) {
That said, you're never even using the value of $count...so it appears as if you could remove it altogether.
Another thing to note is that if you were to use a WP_Query instead of get_posts(), you would have access to a $current_post property for this purpose, without having to manually set up a counter.
I'm trying to display a custom field in a widget I'm customizing but I can't get the custom field to display. I think it has something to do with the variable I'm using to get the post ID in the loop because when I change it to the standard the_title function, the widget works, so it has something to do with how I'm calling the custom field.
I know the key to the custom field is "wpcf-promo-title" but no matter what I've tried, the custom field (which holds a shortened version of the post title for the sidebar) just won't display. This code results in the thumbnails showing, but not the promo title. You can see this in action at http://www.cantstopshipping.com
Here's my code, including the query and the front end of the widget.
function widget($args, $instance) {
extract( $args );
$title = apply_filters( 'widget_title', empty($instance['title']) ? 'Recent Posts' : $instance['title'], $instance, $this->id_base);
$show_date = isset( $instance['show_date'] ) ? $instance['show_date'] : false;
if ( ! $number = absint( $instance['number'] ) ) $number = 5;
if( ! $cats = $instance["cats"] ) $cats='';
// array to call recent posts.
$crpw_args=array(
'showposts' => $number,
'category__in'=> $cats,
);
$crp_widget = null;
$crp_widget = new WP_Query($crpw_args);
echo $before_widget;
// Widget title
echo $before_title;
echo $instance["title"];
echo $after_title;
// Post list in widget
echo "<ul>\n";
while ( $crp_widget->have_posts() )
{
$crp_widget->the_post();
?>
<li class="crpw-item">
<p style="float:left">
<?php the_post_thumbnail('sidebar-small'); ?>
</p>
<?php $promotitle = get_post_meta($post->ID, 'wpcf-promo-title', true); ?>
<p style="float:right; width:200px">
<?php echo $promotitle; ?>
</p>
<?php if ( $show_date ) : ?>
<span class="crpw-date"><?php echo "("; ?><?php echo get_the_date(); ?><?php echo ")"; ?></span>
<?php endif; ?>
</li>
<?php
}
wp_reset_query();
echo "<div class=\"fix\"></div>";
echo "</ul>\n";
echo $after_widget;
}
It looks like your global $post is missing.
But you could try get_the_ID() instead of $post->ID.
You should also consider getting rid of extract(), it's now considered a "bad" practice.
Another thing is that you should use wp_reset_postdata() to restore the global $post object. The wp_reset_query() call should be used with the query_posts() call.