Get a variable from one wordpress template file to another - php

I have a template file (trendingPosts.php) for showing 2 latest posts with the tag 'trending'. In the while loop for displaying these 2 posts, I take their ID's in an array so I can exclude them from the main wordpress loop later:
<div id="trendingWrap" class="clearfix">
<?php
$trending = new WP_Query();
$trending->query("showposts=2&tag=trending");
while($trending->have_posts()) : $trending->the_post();
$wp_query->in_the_loop = true;
$currentTrending[] = $post->ID;
?>
<div class="trendingStory">
<h2 class="trendingTitle"><?php the_title(); ?></h2>
</div><!-- end trendingStory -->
<?php endwhile; ?>
</div><!-- end trendingWrap -->
The problem is that I have an index.php in which I include the loop.php via get_template_part( 'loop', 'index' ); and I am unable to get the $currentTrending[] array that I made in trendingPosts.php. I need to get that array in my loop.php
Moreover, in my loop.php, I am excluding the 2 posts in the following way.
if(have_posts()): while(have_posts()) : the_post();
if( $post->ID == $currentTrending[0] || $post->ID == $currentTrending[1] ) continue;
Is this the right way to exclude posts? if anybody has a better way of doing this whole thing. Please let me know. Of course nothing works until I manage to get that array in loop.php so that is the main issue.
Thanks! I appreciate all the help.

You can easily create variables that you can access everywhere by using the $GLOBALS superglobal array.
Once set
$GLOBALS['mytheme_thisismyvar'] = 22;
You can then access it everwhere in the other templates:
$myvar = $GLOBALS['mytheme_thisismyvar'];
And use it where it suits. This works with sub-templates regardless how they get loaded.
Because the whole program shares this superglobal array, take care that you do not overwrite existing values.

Try moving your current trending code to the theme's functions.php, so that you can call on it whenever you need.
function getCurrentTrending() {
$trending = new WP_Query();
$trending->query("showposts=2&tag=trending");
while($trending->have_posts()) : $trending->the_post();
$wp_query->in_the_loop = true;
$currentTrending[] = $post->ID;
endwhile;
return $currentTrending;
}
You can then fetch that array from any template file:
$currentTrending = getCurrentTrending();
Hope that helps.

Related

Seprate sticky posts from main loop. #WordPress

I need your kind help. I want to seperate sticky posts from main loop (tempate : index.php) and want to add something after sticky posts before rest of loop. Please see the screenshot. Any tip for this custom loop? I'll be gratful.
Screenshot : http://imgur.com/a/e37Pj
Structure is something like :
— These are sticky posts
– sticky post one
– sticky post two
– sticky post three
++ Add something after sticky posts.
— The rest of main loop.
– normal post one
– normal post two.
– normal post three.
Thanks in advance.
Regards
– Pomy
Before standard loop in index you create your area create place where you want to load that "sticky" posts
in post page write this
<ul>
<?php
global $post;
$args = array( 'posts_per_page' => 5, 'offset'=> 1, 'category' => 'Sticky' );
$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
<li>
<?php the_title(); ?>
</li>
<?php endforeach;
wp_reset_postdata();?>
</ul>
This will get you posts from category you want, in this case you will get 5 posts from "sticky" category
Try this:
<?php
$args = array('posts_per_page' => 12, 'post__in' => get_option('sticky_posts'));
$stickyposts = new WP_Query($args);
while($stickyposts->have_posts()) : $stickyposts->the_post();
?>
<!-- sticky posts (max. 12) -->
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<!-- -->
<!-- here you can add random text or a horizontal line with a new headline or s.th.
<!-- like that. This is the exactly place between sticky and normal posts -->
<!-- -->
<?php
$args = array('posts_per_page' => 12, 'post__not_in' => get_option('sticky_posts'));
$normalposts = new WP_Query($args);
while($normalposts->have_posts()) : $normalposts->the_post();
?>
<!-- normal posts without sticky posts (max. 12) -->
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
This will show 12 sticky posts on top of your page. After that you can enter some random text, or s.th. like that, followed by 12 "normal" posts, that are not sticky posts.
Try using an incrementing variable (ie. $counter++) along with a conditional statement within the loop to trigger what you want after looping pass all(3) sticky posts.
<?php
$count=0; //Count is 0 outside of loop
while ( have_posts() ) : the_post(); // Begin WP loop
if(!is_sticky()) : $count++; endif; // Start count for nonsticky loops
if(!is_sticky() && $count==1){
// Do stuff when the first none-sticky post is discovered inside the loop
// ie. Add a div, or insert a class name, etc.
}
// Here is an example of an actual implementation
if(!is_sticky() && $count==1): echo '<div class="not-sticky">'; endif;
// Loop countinues
endwhile; // Loop ends
if(!is_sticky(): echo '</div><!-- .not-sticky -->'; // Placed outside of loop or add inside a conditional statement within the loop to only run once
?>
...Years later, but I hope it may still help someone else who might be facing the same issue.

How to display most viewed posts in custom post type

I'm using keremiya theme for wordpress. I was trying to display my most viewed post in my custom post type if "most_viewed" option is on. The name of my custom post type is watch. How can i do this with my current code? I am also using a plugin called wp-post views to display the views in my sidebar. Here is my query.
<?php if(get_option('most_viewed') == 'On'): ?>
<div class="sidebar-right">
<h2><?php echo get_option('my_title'); ?></h2>
<div class="fimanaortala">
<?php $tavsayi = get_option('keremiya_tavsiyesayi'); $tavkat = get_option('keremiya_tavsiyekat');?>
<?php query_posts('showposts='.$tavsayi.'&v_orderby=desc&cat='.$tavkat.'') ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="filmana">
<div class="filmsol">
<?php keremiya_resim('80px', '70px', 'izlenen-resim'); ?>
</div>
<div class="filmsag">
<div class="filmsagbaslik">
<?php the_title(); ?>
</div>
<div class="filmsagicerik">
<?php if(function_exists('the_views')) { the_views(); echo " "; } ?>
<p><?php nezaman_yazildi(); ?></p>
</div>
<div class="filmizleme">
<img src="<?php bloginfo('template_directory'); ?>/images/filmizle.png" alt="film izle" height="21" width="61" />
</div>
</div>
</div>
<?php endwhile; else: ?>
<?php endif; ?>
<?php wp_reset_query(); ?>
</div>
</div>
Your solution (or attempt, at least), is based on a plugin called WP-PostViews, which I have no knowledge of. So, I can't really help you there. I can, however, help you solve it without this or any other plugin. So here we go:
Wordpress has a little something called metadata. From this very own link:
The Metadata API is a simple and standarized way for retrieving and manipulating metadata of various WordPress object types. Metadata for an object is a represented by a simple key-value pair. Objects may contain multiple metadata entries that share the same key and differ only in their value.
That means you can create metadata for your custom post type that contains how many times it has been seen. To do so, we create a function:
<?php
function set_views($post_ID) {
$key = 'views';
$count = get_post_meta($post_ID, $key, true); //retrieves the count
if($count == ''){ //check if the post has ever been seen
//set count to 0
$count = 0;
//just in case
delete_post_meta($post_ID, $key);
//set number of views to zero
add_post_meta($post_ID, $key, '0');
} else{ //increment number of views
$count++;
update_post_meta($post_ID, $key, $count);
}
}
//keeps the count accurate by removing prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
?>
This will, given the post ID, increment a counter every time a post is viewed. Of course, we have to call this function somewhere in our code so it actually runs. You can do this in two ways: You can either call this function on your single template (which I believe is called single-watch.php), or you can add a simple tracker. I favor the second option, as it keeps your single post loop cleaner. You can achieve such tracking this way:
<?php
function track_custom_post_watch ($post_ID) {
//you can use is_single here, to track all your posts. Here, we're traking custom post 'watch'
if ( !is_singular( 'watch') ) return;
if ( empty ( $post_ID) ) {
//gets the global post
global $post;
//extracts the ID
$post_ID = $post->ID;
}
//calls our previously defined methos
set_views($post_ID);
}
//adds the tracker to wp_head.
add_action( 'wp_head', 'track_custom_post_watch');
?>
There you go. Now, WordPress checks if the user is visiting a page corresponding to a watch single post. If they are, it increments the counter.
The only thing left now is to query for the post with the highest number of views. This is easily achievable using WP_Query. When you create your loop, do something like this:
<?php
$query = new WP_Query( array(
'post_type' => 'watch', //your post type
'posts_per_page' => 1,
'meta_key' => 'views', //the metakey previously defined
'orderby' => 'meta_value_num',
'order' => 'DESC'
)
);
while ($query->have_posts()) {
$query->the_post();
//whatever code you want
}
?>
I kept my answer to PHP, so you can adapt to your mark-up needs. I also assumed your post-type is indeed called watch. I hope all of this helps you. If you want to query your posts in a slightly different way, I suggest you read the WP_Query docs. Cheers.

Hide post from displaying in wordpress

I've inherited a wordpress site and I am having a hard time understanding how posts are being displayed. I want to hide a couple from view (but still be able to give out a URL to view them). I'm not familiar with the way a particular template was coded. The template outputs an image and blurb for each event in a certain category. The meat of code that is spitting this out look like this:
<?php
$args['post_type']='seasonalevents';
$args['posts_per_page']=-1;
$args['orderby'] = 'menu_order';
$activities = new WP_Query( $args );
while ( $activities->have_posts() ) : $activities->the_post();
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'thumb_345_154', true);
?>
Is there any way I can exclude post ID's within the code above? Any hints or tips? Feel totally baffled by this. The variables are defined above this code snippet. I can post if needed.
thanks!
The wordpress-y way to do this would be to add an element to the $args array under the three you already have:
$args['post__not_in'] = array(123,456,789);
Where 123, 456, and 789 are the ids of the posts you want to exlude from showing on this page.
So your whole code would look like:
<?php
$args['post_type']='seasonalevents';
$args['posts_per_page']=-1;
$args['orderby'] = 'menu_order';
$args['post__not_in'] = array(123,456,789);
$activities = new WP_Query( $args );
while ( $activities->have_posts() ) : $activities->the_post();
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'thumb_345_154', true);
?>
Yes there is!
You can get the current post's ID using http://codex.wordpress.org/Function_Reference/get_the_ID
I recommend you looking into 'the loop' and what that is.
This code snippet should do the job :-)
...
$not_these = array(1, 2, 7 /* array with post id's you got somewhere */);
while ( $activities->have_posts() ) : $activities->the_post();
if(in_array(get_the_ID(), $not_these)) continue;
...
The easiest solution is to unpublish that post from your administration panel.
Or
<?php
// The Loop
while($query->have_posts()):
$query->the_post();
if(get_the_ID()!=YOUR_POST_ID):
?>
<!-- Show Post -->
<?php
endif;
endwhile;
?>

Can anybody explain "The Loop" of wordpress?

Im forced to work with wordpress, and if you work with it, you probably know what i mean:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
Its working, no question. But i do not understand what this actually means. Its not a ternary operator nor anything else i know. Ive never seen a statement like this in any php-projects ive worked on. So i got several questions:
What is this line exactly doing? I know that it gets all posts, iterates over them and ... what is this the_post() doing? And what are these doubledots doing?
Is this Wordpress-Only or could it be used somwhere else too?
Where is the current post stored?
Ive already googled it, but there are no information regarding my problem, noone seems to be interested in how wordpress works. I am, but i do not get it. If somebody got an explanation for me, it would be great.
<?php define('WP_USE_THEMES', false); get_header(); ?>
The loop starts here:
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
and ends here:
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
This is using PHP's alternative syntax for control structures, and could also be expressed as:
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//
// Post Content here
//
} // end while
} // end if
?>
the post()
This function does not accept any parameters.
Return Values
This function does not return any values.
<?php
while ( have_posts() ) : the_post();
echo '<h2>';
the_title();
echo '</h2>';
the_content();
endwhile;
?>
have_posts()
Parameters
This function does not accept any parameters.
Return Values
(boolean)
True on success, false on failure.
Examples
The following example can be used to determine if any posts exist, and if they do, loop through them.
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post();
// Your loop code
endwhile;
else :
echo wpautop( 'Sorry, no posts were found' );
endif;
?>
Note
Calling this function within the loop will cause an infinite loop. For example, see the following code:
<?php
while ( have_posts() ): the_post();
// Display post
if ( have_posts() ): // If this is the last post, the loop will start over
// Do something if this isn't the last post
endif;
endwhile;
?>
If you want to check if there are more posts in the current loop without this unfortunate side effect, you can use this function.
function more_posts() {
global $wp_query;
return $wp_query->current_post + 1 < $wp_query->post_count;
}
1. What is LOOP
The Loop is PHP code used by WordPress to display posts. Using The Loop, WordPress processes each post to be displayed on the current page, and formats it according to how it matches specified criteria within The Loop tags.
It will fetch data related to specific page
:(colon) is used to tell condition/loop starts from here. You can replace it with { }(bracket quotes)
<?php
if ( have_posts() ) {
while ( have_posts() ) {
the_post();
//
// Post Content here
//
} // end while
} // end if
?>
2. Is this Wordpress-Only or could it be used somwhere else too?
yes of course you can use it.
You can access full wordpress functionality by including one core file with name of "wp-blog-header.php" that is located on root of wordpress directory.
<?php
/* Short and sweet */
define('WP_USE_THEMES', false);
require('./wp-blog-header.php');
?>
Include this file in the top of your external file, you can access wordpress database, wordpress function , wordpress hooks too.
3. Where is the current post stored?
11 default tables are existed in wordpress database. You can see wp_posts table in database. all posts are store in this table.
suppose, if your are creating meta tag in your post, it will store in wp_postmeta
It's just an alternative syntax for:
if ( have_posts() ) { //open if
while ( have_posts() ) { //start while loop
the_post(); //call a function
See http://php.net/manual/en/control-structures.alternative-syntax.php
It's not wordpress specific and can be used in any php code.
To whom it may concern.
What is WordPress Loop?
When we save data inside WordPress(posts, pages, almost everything) data gets saved as a row inside our database fx. MySQL.
WordPress dynamically query the database and finds which row corresponds to the page you are on, and pulls that data then displays it in that section.
As this is a dynamic query and executed in a repeated manner, it is called a WordPress Loop
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
What are these doubledots doing? condition/loop starts from here :(colon) and is a ternary operators.
I think rest of the questions has been answered by others.

Get ID for static homepage, not post

I am starting to write a custom theme for Wordpress. I have created a new page called 'Home' and set the front page to be a static page, selecting 'Home'. I want this page to show all posts with a category of 'news' plus a couple of images.
I then added front-page.php with the following:
<?php get_header(); ?>
<div class='detail'>
<?php if ( have_posts() ) {
query_posts( 'category_name=news' );
while ( have_posts() ) : the_post(); ?>
<h4><?php the_date('d/m/Y'); ?> - <?php the_title(); ?></h4>
<div class='post'><?php the_content(); ?></div>
<?php endwhile; }?>
</div>
<?php get_footer(); ?>
I've uploaded a couple of images and attached them to the 'Home' page. I now want to get the URL for the attached images. I've tried something like:
$images =& get_children('post_type=attachment&post_mime_type=image&post_parent=' . get_the_ID());
but this only returns the ID of the most recent post being shown, even if I put the above code outside the loop. If I remove the static front page and navigate to the Home page then I get the correct results, any ideas how I can get the images for the Home page when I use it as a static page?
Forgive me if this is simple, first foray into PHP and wordpress development
I think your issue is that you're using get_the_ID(); outside of The Loop. the_ID(); and get_the_ID(); grab the current post ID from the loop; if used outside of The Loop, all you'll get is the last one. See: http://codex.wordpress.org/Function_Reference/get_the_ID
To get the ID of the current page, try:
$page=get_page_by_title($page_name);
$images =& get_children('post_type=attachment&post_mime_type=image&post_parent='.$page->ID);
If that doesn't work, there's a function at http://wordpress.org/support/topic/how-to-get-page-id-using-php?replies=5 (Where I found the above code) that does the same thing.
Hope this helps!

Categories