How to use custom field to add class to a post? - php

I'm trying to add another class to <div class="postthumbnail">. I wanted to style one post different. Therefore, after researching, I found that the best method is to use custom field to add class to the post.
This tutorial, How to style WP posts different, especially this section at bottom, explained how I can add class to the post using the custom field. I did so by giving the custom field a name "en_proceso_class" and the value, "en_proceso" which is an css class. But I'm confused by the last two codes I need to add. The tutorial wasn't clear on where I need to add them.
My original code is:
<?php
// set the "paged" parameter (use 'page' if the query is on a static front page)
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
// the query
$the_query = new WP_Query( 'cat=9&posts_per_page=9&paged=' . $paged );
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php
// the loop
while ( $the_query->have_posts() ) : $the_query->the_post();
?>
<div class="proyectpost">
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="innerpost">
<div class="postthumbnail">
<?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
$image_src = wp_get_attachment_image_src( get_post_thumbnail_id(),'full' );
echo '<img src="' . $image_src[0] . '" width="100%" />';
} ?>
</div>
<div class="posttitle">
<h2><?php the_title(); ?></h2>
<span><?php echo get_post_meta($post->ID, 'location', true); ?></span>
</div><!-- .entry-header -->
<div class="postsubtitle">
<div class="datepanel">
</div>
</div>
</div>
</article><!-- #post-## -->
</div>
<?php endwhile; ?>
<div class="paginationbar">
<?php
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
'format' => '?paged=%#%',
'current' => max( 1, get_query_var('paged') ),
'total' => $the_query->max_num_pages,
'show_all' => True,
'prev_next' => False
) );
?>
</div>
<?php
// clean up after the query and pagination
wp_reset_postdata();
?>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
This is section of the code that I'm trying to add the new code to:
<div class="innerpost">
<?php $custom_values = get_post_meta($post->ID, 'en_proceso_class'); ?>
<div class="postthumbnail <?php en_proceso_class('class-1 class-2 ' . $custom_variable); ?>">
<?php if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
$image_src = wp_get_attachment_image_src( get_post_thumbnail_id(),'full' );
echo '<img src="' . $image_src[0] . '" width="100%" />';
} ?>
</div>
What do I need to do to get it working?

The last part isn't 100% clear but I'll try to answer as best I can.
This piece of code:
$custom_values = get_post_meta($post->ID, 'en_proceso_class');
Gets the value of a post meta field name: 'en_proceso_class'. You actually need to set that first in order for this to work. And you need to add 'true' as another parameter to that function. See here for more info: https://developer.wordpress.org/reference/functions/get_post_meta/
Then there's this:
div class="postthumbnail <?php en_proceso_class('class-1 class-2 ' . $custom_variable); ?>">
Which calls a function named 'en_proceso_class' -- I don't think this is what you want to do. Unless you declared that function beforehand you'll to do something like:
div class="postthumbnail <?php echo 'class-1 class-2 ' . $custom_variable; ?>">
So the whole code put together would look like this:
<div class="innerpost">
<?php
// Get post meta that is already set
$custom_values = get_post_meta($post->ID, 'en_proceso_class', true);
?>
<div class="postthumbnail <?php echo 'class-1 class-2 ' . $custom_values; ?>">
<?php
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
$image_src = wp_get_attachment_image_src( get_post_thumbnail_id(),'full' );
echo '<img src="' . $image_src[0] . '" width="100%" />';
}
?>
</div>
Cheers

Related

I have problem when showing post in loop using WP_Query in Wordpress

i have a problem when trying to show a current 4 post using WP_Query.
But, the older post (The very first post) also shown in the first loop.
This is my code:
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => '3'
);
$query = new WP_Query( $args ); //show 4 post
if ( $query->have_posts() ){
/* Start the Loop */
while ( $query->have_posts() ) {
$query->the_post();?>
<div class="col-md-3 d-flex align-items-stretch">
<div class="card ">
<?php if (has_post_thumbnail()) {
$featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full');
?>
<img class="miniimg" src="<?php echo $featured_img_url; ?>" width="auto" height="200px">
<?php } ?>
<div class="card-body">
<h4><a href="<?php the_permalink(); ?>">
<?php the_title();
$post_date = get_the_date( 'j F Y' );
?>
</a></h4>
<p class="card-text"><?php the_excerpt();?></p>
<div class="d-flex justify-content-between align-items-center">
<div class="btn-group">
<button type="button" class="btn btn-sm btn-primary">Read More</button>
</div>
<small class="text-muted"><?= $post_date; ?></small>
</div>
</div>
</div>
</div>
<?php
$counter++; }
}
?>
This is the result =>
How to fix this problem? is there any problem with my code?
Thankyou.
If specifying 'posts_per_page' => 3 gives back 4 posts, it is almost 100% sure that the first post is a sticky post. Use the option ignore_sticky_posts to ignore them.
$args = array(
'post_type' => 'post',
'posts_per_page' => 4,
'ignore_sticky_posts' => 1,
);
...
A Sticky Post is the post will be placed at the top of the front page of posts. This feature is only available for the built-in post type post and not for custom post types.
Source # https://developer.wordpress.org/themes/functionality/sticky-posts/
I'm pretty sure you applied is sticky to your post from 2012.
To verify you can just add the following to your loop inside the while statement:
<?php //...
while( have_posts() ): the_post();
if( is_sticky() ):
echo 1;
else: echo 0;
endif;
endwhile;
//... ?>
Or go to you post in the admin console, and verify that you didn't check the "is sticky" checkbox on the right side in the publish panel.
<?php
$args = array( 'post_type' => 'movies');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
?><div class="movie-content" >
<?php
echo '<a href="' . get_permalink( $post->ID ) . '" title="' . esc_attr( $post->post_title ) . '">' ?>
<h2><?php echo the_title(); ?></h2>
<div><?php the_post_thumbnail('thumbnail'); ?></div>
<div class="excerpt"><?php the_excerpt(); ?></div>
<?php
the_content();
echo '<div class="entry-content">';
echo '</div>';
echo "</div></a>";
endwhile;
?>

Display ACF field inside posts loop in category.php

OK, so I need to display ACF custom field inside my posts loop in my custom category.php file. Here is the loop:
<div class="container">
<div class="row">
<?php
if ( have_posts() ) : ?>
<?php
/* Start the Loop */
while ( have_posts() ) : the_post();
?>
<div class="col-xs-12 col-sm-4">
<?php the_title( '<h2>', '</h2>' ); ?>
<div><?php MY_ACF_FIELD_GOES_HERE ?></div>
</div>
<?php
/* End the Loop */
endwhile;
?>
</div><!-- .row -->
</div><!-- .container -->
As you can see loop displays pages from category (titles), but I need also display short description. I know I could use:
<?php the_excerpt(); ?>
But not in this case because excerpt contains text that I do not need inside loop. So I need to create my own short description field for every page. How can I display it in category.php template? Custom field (my own short desc) is on all pages.
You can retrieve the ACF field value using get_field('field_name'). Example-
<?php
$args = array( 'post_type' => 'speakers', 'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="entry-content">';
echo '<h2 class="speaker-name">';
the_title();
echo '</h2>';
echo '<img src="' . get_field('field_name') . '" alt="" />';
echo '<span class="speaker-title">';
the_field('title'); echo ' / '; the_field('company_name');
echo '</p>';
the_content();
echo '</div>';
endwhile;
?>

Pagination not working on Post name permalink but working on plain permalink

I am trying to loop through a post type called blog. The pagination works fine when the Wordpress permalinks are set to plain however when I change it to post the name and click to go on pagination link, it loads a 404 error.
I found out that you can't have the same post type and page name since it will cause a 404 error. I wanted to know if there was a workaround because changing the name of the post type will affect the blog posts.
My page-blog.php
<?php
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$loop = new WP_Query( array( 'post_type' => 'blog',
'posts_per_page' => 2,
'paged' => $paged,
'has_archive' => false,
'rewrite' => array(
'slug' => '/blog', // if you need slug
'with_front' => false,
),)
);
if ( $loop->have_posts() ):
while ( $loop->have_posts() ) : $loop->the_post();
// Set variables
$title = get_the_title();
$post_date = get_the_date('M j');
$amount_of_time_to_read = get_field('amount_of_time_to_read');
?>
<a href="<?php the_permalink(); ?>" class="post-blog-link">
<div class="post">
<?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'thumbnail' ); ?>
<div class="post-image-v2" style="background-image:url('<?php echo $url ?>');">
</div>
<div class="post-content-v2">
<h2 class="post-title"><?php echo $title; ?></h2>
<div class="post-excerpt">
<p><?php echo get_excerpt(); ?></p>
</div>
<p class="post-date"> <span class="caps"><?php echo $post_date; ?></span> | <?php echo $amount_of_time_to_read; ?>min read</p>
</div>
</div>
</a>
<!--
-->
<?php endwhile; ?>
<center>
<div class="pagination mt-25">
<?php pagination_bar( $loop ); ?>
</div>
</center>
<?php wp_reset_postdata();
endif;
?>
My functions.php
add_action('init', 'custom_rewrite_basic');
function custom_rewrite_basic() {
global $wp_post_types;
foreach ($wp_post_types as $wp_post_type) {
if ($wp_post_type->_builtin) continue;
if (!$wp_post_type->has_archive && isset($wp_post_type->rewrite) && isset($wp_post_type->rewrite['with_front']) && !$wp_post_type->rewrite['with_front']) {
$slug = (isset($wp_post_type->rewrite['slug']) ? $wp_post_type->rewrite['slug'] : $wp_post_type->name);
$page = get_page_by_slug($slug);
if ($page) add_rewrite_rule('^' .$slug .'/page/([0-9]+)/?', 'index.php?page_id=' .$page->ID .'&paged=$matches[1]', 'top');
}
}
}
function get_page_by_slug($page_slug, $output = OBJECT, $post_type = 'page' ) {
global $wpdb;
$page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_name = %s AND post_type= %s AND post_status = 'publish'", $page_slug, $post_type ) );
return ($page ? get_post($page, $output) : NULL);
}
what do you want to achieve to have a Post Type and Page to be of the same slug?
As per my understanding you want to display the archive of your custom post type "Blog". All you have to do is create a file name archive-blog.php and use the plain WordPress loop. That way you don't need to have a page-blog.php (Delete it) to display the Archives of your "Blog" post type. yourwebsite.com/blog will automatically display your "Blog" archive.
Use the code below to paste in your archive-blog.php
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post();
// set vars
$amount_of_time_to_read = get_field('amount_of_time_to_read');
?>
<a href="<?php the_permalink(); ?>" class="post-blog-link">
<div class="post">
<?php $url = wp_get_attachment_url( get_post_thumbnail_id( $post->ID ), 'thumbnail' ); ?>
<div class="post-image-v2" style="background-image:url( '<?php echo $url ?>' );">
</div>
<div class="post-content-v2">
<h2 class="post-title"><?php the_title(); ?></h2>
<div class="post-excerpt">
<p><?php the_excerpt(); ?></p>
</div>
<p class="post-date"> <span class="caps"><?php the_date( 'M j' ); ?></span> | <?php echo $amount_of_time_to_read; ?>min read</p>
</div>
</div>
</a>
<?php endwhile; ?>
<?php
// You need to tweak this function, it shouldn't be needing a $loop var to work
// paste the function here and may be we will take a look at that
// pagination_bar( $loop );
the_posts_pagination();
?>
<?php else : ?>
<?php // No Posts Found ?>
<?php endif; ?>
Had to add this to my functions.php
add_rewrite_rule('^blog/page/([0-9]+)','index.php?pagename=blog&paged=$matches[1]', 'top');

wp_get_attachment_image not working wordpress to show blog post image

I am using wordpress and trying to create a blog landing page to show the most recent blog posts. So far so good but I am having difficulties showing the blog image in the image tag. I am able to obtain the postId by using get_the_id function. I was also able to get the date of the post by using the_date function.
However, I cannot get the wp_get_attachment_image function to show the image of the blog post.
Please see my code below.
<?php $query = new WP_Query( 'posts_per_page=5' ); ?>
<?php while ($query -> have_posts()) : $query -> the_post(); ?>
<div class="blog">
<img src="wp_get_attachment_image( get_the_ID() ); ">
<h3><?php the_title(); ?></h3>
<p><?php the_date(); ?></p>
<p><?php the_excerpt(__('(more…)')); ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
Use following code for get the attached image.
<img src="<?php echo wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium');?>">
The function wp_get_attachment_image is waiting for attachement_id.
See below in wp, how we get all attachments from a post :
<?php if ( $post->post_type == 'data-design' && $post->post_status == 'publish' ) {
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->ID,
'exclude' => get_post_thumbnail_id()
) );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
}
}
}
?>
I had to use the following function the_post_thumbnail() and echo the result within an image tag
<img src="<?php echo the_post_thumbnail();?>">
The following code worked.
<?php $query = new WP_Query( 'posts_per_page=5' ); ?>
<?php while ($query -> have_posts()) : $query -> the_post(); ?>
<div class="blog">
<img src="wp_get_attachment_image( get_the_ID() ); ">
<h3><?php the_title(); ?></h3>
<p><?php the_date(); ?></p>
<p><?php the_excerpt(__('(more…)')); ?></p>
</div>
?>

Wordpress loops efficiency

I build this site with wordpress:
http://mida.org.il/
As you can see, homepage takes a lot of time to load.
I'm trying to fix this - there are five custom loops in that page, three of them using posts_per_page and cat to query posts, and posts_per_page set to 3.
My question is, if the loop gets to the third post, it stops and and breaks out, or its keep looping until it gets to the last post?
If the second is correct, no wonder that it's so slow, this site holds thousands of posts.
The code for the loops:
if ( $first_special_cat ){
$args = array( 'cat'=>$first_special_cat, 'posts_per_page'=>3, 'orderby'=>'date', 'post__not_in'=>$sticky );
$cat_name = $first_special_cat;
$cat_id = get_cat_ID($first_special_cat);
}else{
$args = array( 'cat'=>50, 'posts_per_page'=>3, 'orderby'=>'date', 'post__not_in'=>$sticky );
$cat_name = get_cat_name(50);
$cat_id = 50;
}
$the_query = new WP_Query($args);
echo '<div class="special-proj-main-title">';
echo '<div class="homepage-blueline-title"></div>';
echo '<h4 class="special-cat-name"><a href="' . esc_url( get_term_link($cat_id) ) . '">' . $cat_name . '</h4>';
echo '</div>';
?>
<div class="row">
<div class="col-sm-4">
<?php if ( $the_query->have_posts() ): ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); //Setting the three posts to the right: ?>
<h2 class="special-project-title"><a class="special-proj-title-link" href="<?php echo esc_url( get_the_permalink() )?>"><?php the_title()?></a></h2> <br/>
<div class="post-meta special-project-meta"><?php mida_post_meta()?></div><br/>
<?php
endwhile;
wp_reset_postdata(); ?>
<span class="to-all-posts"><?php echo sprintf( __('Load more posts from %s', 'mida'), $cat_name ); ?></span>
<?php
else:
echo "You put wrong id";
endif;
?>
</div>
<div class="col-sm-8 home-background-img">
<?php
if ( $first_special_post )
$args = array('name' => $first_special_post, 'posts_per_page' => 1 );
else
$args = array('cat'=>50, 'posts_per_page' => 1, 'orderby'=>'date' );
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ):
while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php
$first_special_img = get_field('rectangular_image');
if ( $first_special_img )
$first_special_img_src = wp_get_attachment_image_src( $first_special_img['id'], 'full' );
else
$first_special_img_src = wp_get_attachment_image_src( get_post_thumbnail_id(), 'full' );
?>
<div class="special-project-section" style="background: url('<?php echo $first_special_img_src[0]; ?>');background-size: contain;">
<a href="<?php echo esc_url( get_the_permalink() )?>" title="<?php the_title() ?>"><span style="
position:absolute;
width:100%;
height:100%;
top:0;
left:0;
z-index: 1;"></</span>
</a>
<?php
echo '<div class="special-cat-on-img">';
echo $first_special_text ? '<h5><div class="special-cat-name-img">' . $first_special_text . '</div></h5>' : '<h5><div class="special-cat-name-img">' . __('Special Project', 'mida') . '</div></h5>'; ?>
<h6 class="speical-cat-title-img"> <?php the_title() ?> </h6>
<?php echo '</div>'; ?>
<div class="blue-line"><?php echo '<div class="special-proj-ex">' . $first_special_cat_ex . '</div>'; ?></div>
</div>
<?php
endwhile;
wp_reset_postdata();
endif;
?>
</div>
</div>
X3.
every loop query different categories ( $first_special_ are custom fields, input from the user ).
So can anyone help me optimize this code (and answer the above question)?
Thanks!
You problem is NOT in your loop but rather in the page itself. Total page size is a whopping 11.8MB! This looks primarily due to a ton of images. You might try a little image optimization (use jpg's for post thumbs/images) and make sure images are sized correctly. Honestly, lazy loading might be a good solution here! There are plenty of options out there to make it easy to implement.

Categories