I am trying to add custom divs into my index page and I created some page templates, that i was thinking of using as a way to filter out the pages. So basically if the post uses 'Media template' it would be displayed in that div.
But I am struggling in writing the proper php code that would loop trough all the posts and find the post that uses this template.
In the end I want to find a post/page that uses 'Media template' and post it's content in the folowwing div:
<div class="home-media-content col-sm-3 px-1 pb-2">
<div class="embed-responsive embed-responsive-16by9">
<?php
$pages = get_pages();
foreach ($pages as $page) {
echo $page->post_title; //Posting just for the test
echo $page->template; //SHOULD GET THE TEMPLATE and if the template name is 'Media template' display post content
}
?>
</div>
</div>
I am not sure if it is the best way of displaying custom things so any better suggestions are welcome!
Edited to use WP_Query
See below for how I'd do it, using the setup_postdata() and get_page_template() functions. I think you should be able to get this info from the '_wp_page_template' meta for each page if you don't want to setup postdata, but if you're going to be doing a proper loop anyway then the latter is probably easiest.
<div class="home-media-content col-sm-3 px-1 pb-2">
<div class="embed-responsive embed-responsive-16by9">
<?php
$my_query = new WP_Query(
array(
'post_status' => 'publish',
'post_type' => 'page',
)
);
if ( $my_query->have_posts() ) {
while ( $my_query->have_posts() ) {
$my_query->the_post();
the_title(); // Posting just for the test
if ( get_page_template() === 'media-template.php' ) { // This needs to be the file slug rather than template name
do_something();
} else {
do_something_else();
}
}
}
wp_reset_postdata(); // Reset postdata back to normal
?>
</div>
</div>
Related
Dear PHP / Wordpress / Dev Experts,
Ive build a plugin, with a custom post type and some advanced custom fields. The main goal is to list the members in my band, with pictures and name.
You can see it here: http://www.lucky13.nl/test/
I've managed to get everything working to my taste, however.. I have 5 bandmembers in my band which i've added, but i'm only seeing 4. Where is the 5th entry / post? I find that the first added bandmember is not displaying.
I assume this has to do with the loop, and the array not listing all items? But i'll leave this to the experts.. I would appreciate any comments of help!
My code:
<?php
/*
Plugin Name: VrolijkWebdesign - Bandmembers
Description: For a bandwebsite to show bandmembers.
*/
/* Start Adding Functions Below this Line */
/* NAME FUNCTION */
function new_section_1(){
$bandmembers = new WP_Query(array(
'post_type' => 'bandmembers'
));
while($bandmembers->have_posts()) : $bandmembers->the_post();
if (has_post_thumbnail( $post->ID ) ):
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
<!-- START HTML -->
<div class="span2">
<figure class="snip1104">
<img src="<?php echo $image[0] ;?>" alt='sample33'/>
<figcaption>
<h5> <?php the_field('firstname'); ?> <span> <?php the_field('lastname'); ?>
</span></h5>
</figcaption>
</figure>
</div>
<!-- END HTML -->
<?php endif;
endwhile;
}
add_shortcode('band', 'new_section_1');
?>
$bandmembers = new WP_Query(array(
'post_type' => 'bandmembers',
'posts_per_page' => '5'
));
Try setting the posts_per_page argument. Since the default might be set to '4' by other filters.
If you want to get all posts in a single query use '-1' instead of '5'
You could also try the below for debugging purposes only:
-Try to set post_status to 'any' to make sure that post statuses are not a problem.
-Try var_dump($bandmembers) after doing the query to see the fetched posts before the loop starts.
I have an 'apparel' section on this HTML website which I'm now converting to Wordpess.
In my design it looks like this (see below)
Apparel section
but in my build it looks like this (see below)
The actual build in wordpres
I don't think the code is the problem but here it is for reference:
<?php $loop = new WP_Query( array('post_type' => 'apparel', 'orderby' => 'post_id', 'order' => 'ASC')); ?>
<?php while( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="col-lg-4 col-md-6 col-sm-6 mb-sm-30">
<div class="blog-post">
<div class="post-media">
<img class="item-container" src="<?php the_field('apparel_img'); ?>"/>
</div>
<div class="product"><a><?php the_field('name_price');?></a></div>
</div>
</div>
<?php endwhile; ?>
When I've used Chrome inspector to check what's happening with the images themselves it looks like other strings are being pulled in, and when I delete everything apart from the image root then the image isn't broken and works.
src="26, frontrunnerz black tee, black tee, , , image/png, http://localhost:8888/wp-content/uploads/2016/09/tee01.png, 300, 200, Array"
Appreciate your help with this please!
Do you have your ACF field of apparel_image outputting the array rather than URL? To output it in this way you'd want URL!
Or if you want control of the size of image being pulled through you could output ID from ACF and put in your template:
$x = //post id;
$s = //size string e.g. 'full';
$image = get_field('apparel_image', $x);
echo wp_get_attachment_image( $image, $s );
As a final note, the below site has their docs, which are really handy if you're trying to do something more complicated, but I'm pretty sure if you want to just output the src, you just need to change the output in your wp-admin custom field settings!
https://www.advancedcustomfields.com/resources/image/
Hi I am having an issues with custom post type.
So what I am trying to do, list all posts from subcategories while calling a main category. Usualy this worked with no problem with normal post type from Wordpress, but since I tried to use custom post type it's not working...
My category structure is like this:
Category
Sub category
( Posts inside )
Sub category
( Posts inside )
Any help or tips are appreciated. Thanks
<?php
$categories = get_categories('title_li=&hide_empty=1&parent=1430');
foreach($categories as $category) {
echo "<div class='col-12' style='border-bottom: 0'><h1 class=''>".$category->name."</h1></div>";
$args = array('cat'=> $category->term_id);
if (have_posts() ) : while (have_posts() ) : the_post(); ?>
<!-- article -->
<article class="col-3">
<div class="image">
<span class="helper"></span><?php the_post_thumbnail('full');?>
</div>
<h1><?php the_title(); ?></h1>
<?php the_content();?>
</article>
<!-- /article -->
<?php endwhile; endif; }?>
</main>
There are a couple of problems going on here:
First, you're not declaring a loop, or calling get_posts.
Second, if you check out the documentation for WP_Query (which is the "backbone" behind get_posts, so the arguments are essentially the same), you'll see that if you do NOT pass in an argument for post type, the default is post.
So, since you've not shared with us the post type, you'll have to adjust the below as needed:
// .. your code above ....
$args = array(
'cat'=> $category->term_id,
// Include the post_type in the query arguments
'post_type' => 'custom-post-type' // Change this as needed
);
// Now we need to actually query for the posts...
$custom_posts = new WP_Query( $args );
// These are modified to use our custom loop...
if ($custom_posts->have_posts() ) : while ($custom_posts->have_posts() ) : $custom_posts->the_post(); ?>
// .. your code below ... the_title(), etc will work here...
I ran into a little problem and I might need your help to sort it out.
I an building a website that uses custom taxonomies and tags posts accordingly. So, there is a page like http://example.com/custom-taxonomy/term that displays all the posts tagged with "term".
The visitor should be able to go to http://example.com/custom-taxonomy/ and see a lists of all the terms that are used inside that custom taxonomy in order to browse them. This list should also be "paginated" since some taxonomies could have quite a lot of terms in them.
Any ideas on how I should handle this?
Thanks a bunch!
I'll answer my own question here, maybe it will help others.
I have created a custom page template that uses get_terms to get the terms for a specific taxonomy and iterates through them displaying them in the desired manner.
I then created a page with the exact same slug as the main taxonomy slug (http://example.com/actors in this case) and thus when going to /actors/ you actually see the page created that acts as an index page for the taxonomy. You can see it in effect at http://couch.ro/actori/
In the actual code I am also using the Taxonomy Images plugin for having images on the actual tags so the get_terms is executed through the apply_filter() function. You have the full code for the template below. Any feedback is highly appreciated!
<?php
/*
Template Name: Taxonomy Index
*/
$slug_to_taxonomy=array('actori'=>'actor','regizori'=>'director');
$terms_per_page=get_option( 'c2c_custom_post_limits' );
if ($terms_per_page['archives_limit']==0)
{
$terms_per_page=get_options('posts_per_page');
}
else
{
$terms_per_page=$terms_per_page['archives_limit'];
}
$slug=$post->post_name;
if (!isset($slug_to_taxonomy[$slug]))
{
header("Location: /");exit;
}
else
{
$taxonomy=$slug_to_taxonomy[$slug];
}
$terms_page=get_query_var('paged');
if (empty($terms_page))
{
$terms_page=1;
}
$terms=apply_filters( 'taxonomy-images-get-terms', '',array('having_images'=>false,'taxonomy'=>$taxonomy, 'term_args'=>array('offset'=>($terms_page-1)*$terms_per_page,'number'=>$terms_per_page)) );
if (empty($terms))
{
header("Location: /");exit;
}
$processed_terms=array();
foreach ($terms as $term)
{
if (!empty($term->image_id))
{
$image_src=wp_get_attachment_image_src($term->image_id,'archive-thumbnail');
$image_src=$image_src[0];
}
else
{
$image_src='http://couch.ro/wp-content/uploads/couchie_75.png';
}
$term_posts=get_posts(array('posts_per_page'=>3,'tax_query'=>array(array('taxonomy'=>$taxonomy,'field'=>'slug','terms'=>$term->slug))));
$actual_term_posts=array();
foreach ($term_posts as $post)
{
$actual_term_posts[$post->post_title]=get_permalink($post->id);
}
$processed_terms[]=array(
'name'=>$term->name,
'description'=>$term->description,
'url'=>get_term_link($term),
'image'=>$image_src,
'posts'=>$actual_term_posts,
'count'=>$term->count
);
}
$has_next_page=(isset($processed_terms[$terms_page]));
get_header();
?>
<div class="posts-wrap">
<div class="archive-title_wrap"><h1 class="archive-title"><?php the_title(); ?></h1></div>
<div id="post_list_wrap">
<?php
foreach ($processed_terms as $term)
{
echo "<div class='post post-archive'>
<a href='{$term['url']}' title='{$term['name']}'><img src='{$term['image']}' alt='{$term['name']}'></a>
<div class='rating' style='text-align:right;'>{$term['count']} ".($term['count']==1?'review':'reviewuri')."</div>
<h2 class='index-entry-title'>
<a href='{$term['url']}' title='{$term['name']}'>{$term['name']}</a>
</h2>
<div class='archive-meta entry-meta-index'>
<span>";
$first_term_post=true;
foreach ($term['posts'] as $title=>$link)
{
echo ($first_term_post?'':', ')."<a href='{$link}' title='{$title}'>{$title}</a>";
$first_term_post=false;
}
echo "</span>
</div>
</div>";
}
?>
</div>
<?php if ($terms_page>1 OR $has_next_page) { ?>
<div class="navigation">
<div class="nav-prev left"><?php if ($terms_page>1) echo "<a href='/{$slug}/".($terms_page>2?"page/".($terms_page-1)."/":'')."'>".__('« Previous Page', 'designcrumbs')."</a>"; ?></div>
<div class="nav-next right"><?php if ($has_next_page) echo "<a href='/{$slug}/page/".($terms_page+1)."/'>".__('Next Page »', 'designcrumbs')."</a>" ?></div>
<div class="clear"></div>
</div>
<?php } ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
You can use query_posts function like this
$termname = get_query_var('pagename'); //custom-taxonomy term
query_posts(array(
'post_type' => POST_TYPE,
'showposts' => $limit,
'custom-taxonomy' => $termname // use $term1.','.$term2.','.$term3 to get multiple terms posts
));
see Documentation at Wordpress
To get all Terms under Custom Taxonomy try this you will have full control.
global $wpdb;
$taxonomy = CUSTOM_CAT_TYPE;
$table_prefix = $wpdb->prefix;
$wpcat_id = NULL;
//Fetch category or Term as said
$wpcategories = (array) $wpdb->get_results("
SELECT * FROM {$table_prefix}terms, {$table_prefix}term_taxonomy
WHERE {$table_prefix}terms.term_id = {$table_prefix}term_taxonomy.term_id
AND {$table_prefix}term_taxonomy.taxonomy ='" . $taxonomy . "' and {$table_prefix}term_taxonomy.parent=0 ORDER BY {$table_prefix}terms.name ASC");
$wpcategories = array_values($wpcategories);
foreach ($wpcategories as $wpcat) {
$termid = $wpcat->term_id;
$name = $wpcat->name;
$termprice = $wpcat->term_price;
$tparent = $wpcat->parent;
}
i am creating a related post article feature for my wordpress enabled site.being new to php and wordpress facing some issue.
though i can user wordpress build in feature to show related post of author but since site is hosting articles of authors who don't have any profile with us and there are many such authors so when a new post is being created for the author we tend to save a custom field as author_email.
so based on this we want to show all post being published of a particual author.i tried using get_posts() method
<?php
$args = array( 'meta_key' => 'author_email', 'meta_value' => 'XYZ#XYZ.com');
$authorposts=get_posts($args); ?>
<div id="content">
<span class="breadcrumbs">Home » <?php the_category(', ') ?></span>
<?php if (count( $authorposts ) > 0) {
foreach ( $authorposts as $post ): setup_postdata($post) ?>
<div id="headline_author">
/*
showing post tilte with image and some part of it
*/
<div class="clearfloat"></div>
</div>
<?php endforeach; ?>
<div class="post-nav">
<div class="previous"><?php previous_posts_link('‹ Previous Page') ?></div>
<div class="next"><?php next_posts_link('Next Page ›') ?></div>
</div>
<?php
} else {
echo '<p>No articles by this user</p>';
}
?>
</div>
it showing the first 5 results and a link to the next page but when i click on the next page it show me that it has gone to second page as its also visible on the URL but its showing the same 5 results what it has shown in the first page.
i am an idea that the query i have written on the same page is getting executed again from the beginning but not sure how to fix it.
since i am using cutom fields to get posts i can use simple query to fetch post based on the limit or offse etc.
can any one help me to fix the things or can point me hw to do it in right way
thanks in advance
I am not word-press/php expert just started learning about it. it seems that you have not set the paged global variable by which it can track the page number.
you need to do something like this.
$post_per_page = get_option('posts_per_page');
if (!is_paged()) {
$custom_offset = 0;
} else {
$custom_offset = $post_per_page*($paged-1);
}
$args = array( 'meta_key' => 'author_email', 'meta_value' => xyz#xyz.com' ,'numberposts' => $post_per_page,'offset' => $custom_offset);