code arrangement inside wordpress loop - php

This is the actual code for the loop:
<div id="content" class="span9" role="main">
<?php if ( have_posts() ){
// Do we have any posts in the databse that match our query?
?>
<?php
get_template_part( 'inc/post-format/single', get_post_format() );
$enable_rtl = of_get_option('enable_rtl', false);
if(!of_get_option('disable_pagination')){
if($enable_rtl){
$next_post = get_adjacent_post( false, '', true );
$prev_post = get_adjacent_post( false, '', false );
}else{
$next_post = get_adjacent_post( false, '', false );
$prev_post = get_adjacent_post( false, '', true );
}
?>
<?php
}
// show related posts by tag
if(!of_get_option('disable_related_posts')){
get_template_part( 'inc/related-posts' );
}
endwhile; // OK, let's stop the post loop once we've displayed it
// If comments are open or we have at least one comment, load up the default comment template provided by Wordpress
if ( comments_open() )
comments_template( '', true );
}else{ // Well, if there are no posts to display and loop through, let's apologize to the reader (also your 404 error) ?>
<article class="post error">
<h1 class="404"><?php _e('Page not found', 'outbox'); ?></h1>
</article>
<?php } // OK, I think that takes care of both scenarios (having a post or not having a post to show) ?>
</div><!-- #content .site-content -->
This is the snippet which I want to add:
// Parent CPT
if ( 'cpt-parent' == wpse121567_get_cpt_hierarchy() ) {
// Normal loop here
if ( have_posts() ) : while ( have_posts() ) : the_post();
// Normal loop markup
endwhile; endif;
}
// Child CPT
else if ( 'cpt-child' == wpse121567_get_cpt_hierarchy() ) {
// Globalize post object
global $post;
// Output Parent CPT title and content
$parent = get_post( $post->post_parent );
echo '<h1>' . $parent->post_title . '</h1>';
echo '<div>' . apply_filters( 'the_content', $parent->post_content ) . '</div>';
// Fetch parent CPT comments
$parent_cpt_comments = get_comments( array(
'post_id' => $post->post_parent,
'status' => 'approve'
) );
// Loop through parent CPT comments
foreach ( $parent_cpt_comments as $comment ) {
// Output comment list markup here
}
}
// Grandchild CPT
else if ( 'cpt-grandchild' == wpse121567_get_cpt_hierarchy() ) {
// Comment Stats code goes here
}
This is how I added it inside my actual code:
<div id="content" class="span9" role="main">
<?php if ( 'cpt-parent' == wpse121567_get_cpt_hierarchy() ) {
// Normal loop here
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part( 'inc/post-format/single', get_post_format() );
endwhile; endif;
}
// Child CPT
else if ( 'cpt-child' == wpse121567_get_cpt_hierarchy() ) {
// Globalize post object
global $post;
// Output Parent CPT title and content
$parent = get_post( $post->post_parent );
echo '<h1>' . $parent->post_title . '</h1>';
echo '<div>' . apply_filters( 'the_content', $parent->post_content ) . '</div>';
// Fetch parent CPT comments
$parent_cpt_comments = get_comments( array(
'post_id' => $post->post_parent,
'status' => 'approve'
) );
// Loop through parent CPT comments
foreach ( $parent_cpt_comments as $comment ) {
// Output comment list markup here
}
}
// Grandchild CPT
else if ( 'cpt-grandchild' == wpse121567_get_cpt_hierarchy() ) {
// Comment Stats code goes here
}
?>
<?php
$enable_rtl = of_get_option('enable_rtl', false);
if(!of_get_option('disable_pagination')){
if($enable_rtl){
$next_post = get_adjacent_post( false, '', true );
$prev_post = get_adjacent_post( false, '', false );
}else{
$next_post = get_adjacent_post( false, '', false );
$prev_post = get_adjacent_post( false, '', true );
}
?>
<?php
}
// show related posts by tag
if(!of_get_option('disable_related_posts')){
get_template_part( 'inc/related-posts' );
}
endwhile; // OK, let's stop the post loop once we've displayed it
// If comments are open or we have at least one comment, load up the default comment template provided by Wordpress
if ( comments_open() )
comments_template( '', true );
}else{ // Well, if there are no posts to display and loop through, let's apologize to the reader (also your 404 error) ?>
<article class="post error">
<h1 class="404"><?php _e('Page not found', 'outbox'); ?></h1>
</article>
<?php } // OK, I think that takes care of both scenarios (having a post or not having a post to show) ?>
</div><!-- #content .site-content -->
And I'm getting this error: P**arse error: syntax error, unexpected T_ENDWHILE** in this line: endwhile;
I'm sure is something wrong on how I added the code but it's very confusing for me because the actual code has a lot of php tags around...
Any suggestion? Thanks!

i have changed ,try below code
<div id="content" class="span9" role="main">
<?php if ( 'cpt-parent' == wpse121567_get_cpt_hierarchy() ) {
// Normal loop here
if ( have_posts() ) : while ( have_posts() ) : the_post();
get_template_part( 'inc/post-format/single', get_post_format() );
endwhile; endif;
}
// Child CPT
else if ( 'cpt-child' == wpse121567_get_cpt_hierarchy() ) {
// Globalize post object
global $post;
// Output Parent CPT title and content
$parent = get_post( $post->post_parent );
echo '<h1>' . $parent->post_title . '</h1>';
echo '<div>' . apply_filters( 'the_content', $parent->post_content ) . '</div>';
// Fetch parent CPT comments
$parent_cpt_comments = get_comments( array(
'post_id' => $post->post_parent,
'status' => 'approve'
) );
// Loop through parent CPT comments
foreach ( $parent_cpt_comments as $comment ) {
// Output comment list markup here
}
}
// Grandchild CPT
else if ( 'cpt-grandchild' == wpse121567_get_cpt_hierarchy() ) {
// Comment Stats code goes here
?>
<?php
$enable_rtl = of_get_option('enable_rtl', false);
if(!of_get_option('disable_pagination')){
if($enable_rtl){
$next_post = get_adjacent_post( false, '', true );
$prev_post = get_adjacent_post( false, '', false );
}else{
$next_post = get_adjacent_post( false, '', false );
$prev_post = get_adjacent_post( false, '', true );
}
?>
<?php
}
// show related posts by tag
if(!of_get_option('disable_related_posts')){
get_template_part( 'inc/related-posts' );
}
// If comments are open or we have at least one comment, load up the default comment template provided by Wordpress
if ( comments_open() )
comments_template( '', true );
}else{ // Well, if there are no posts to display and loop through, let's apologize to the reader (also your 404 error) ?>
<article class="post error">
<h1 class="404"><?php _e('Page not found', 'outbox'); ?></h1>
</article>
<?php } // OK, I think that takes care of both scenarios (having a post or not having a post to show) ?>

Related

WooCommerce display product thumbnail and add to cart button

I have created a live search field that fetches the title of the product using AJAX.
It works correctly, however, I would like to fetch the product thumbnail and the ‘Add to the cart’ button.
**Edit: I have added the output for the thumbnail and add to cart button. It works, but it only displays in singular rows. How can I update my output in rows of 4 as below?
Front End Code
<input type="text" name="keyword" id="keyword" onkeyup="fetch()">
<div id="datafetch">Your numbers will show here</div>
<script>
function fetch(){
$.post('<?php echo admin_url('admin-ajax.php'); ?>',{'action':'my_action'},
function(response){
$('#datafetch').append(response);
console.log(result);
});
}
</script>
Code in Functions.php
<?php
}// LOTTERY start the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'product' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post();
global $product;
$product = get_product( get_the_ID() ); //set the global product object
$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {?>
<h4><?php the_title();?></h4>
<h4><?php the_post_thumbnail();?></h4>
<p><?php echo $product->get_price_html(); ?></p>
<?php woocommerce_template_loop_add_to_cart(); //ouptput the woocommerce loop add to cart button ?>
<?php
}
endwhile;
wp_reset_postdata();
endif;
die();
}
You can use this get_the_post_thumbnail_url(get_the_ID()) to get thumbnail URL and add image.
You can use this https://yourdomain.com/?add-to-cart=<product_id> to add product add to cart URL.
https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/
Try this approach
//Ajax
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'product' ) );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post();
$myquery = esc_attr( $_POST['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) {
//get image and add-to-cart buttom here
$query->the_post();
global $product;
wc_get_template_part('content', 'product');
//End get image and add-to-cart buttom here
}
endwhile;
wp_reset_postdata();
endif;
die();
}

Add a class to the body - PHP Wordpress

I am trying to add a class to the body in a WordPress theme so that when there are no posts on a page it will not show the search bar. I have in my functions.php right now this to look for one certain page, and if there are no posts.
<?php
add_filter( 'body_class', 'custom_class' );
function custom_class( $classes ) {
if(strpos($_SERVER['REQUEST_URI'], 'agent') !== false ){
$classes[] = 'noSearchBar';
}
if(!have_posts() ){
$classes[] = 'noSearchBar';
}
return $classes;
}
?>
Which works for most of the pages, but on some pages it is using a different template so instead of calling the posts with have_posts like this:
<?php
global $wp_query;
if ( have_posts() ) :
while ( have_posts() ) : the_post();
get_template_part('template-parts/property-for-listing');
endwhile;
wp_reset_postdata();
else:
?>
<h4><?php esc_html_e('Sorry No Results Found', 'houzez') ?></h4>
<?php
endif;
?>
Its is bringing it up like this:
<?php
global $wp_query, $paged;
if(!$fave_prop_no){
$posts_per_page = 9;
} else {
$posts_per_page = $fave_prop_no;
}
$latest_listing_args = array(
'post_type' => 'property',
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'post_status' => 'publish'
);
$latest_listing_args = apply_filters( 'houzez_property_filter', $latest_listing_args );
$latest_listing_args = houzez_prop_sort ( $latest_listing_args );
$wp_query = new WP_Query( $latest_listing_args );
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
get_template_part('template-parts/property-for-listing');
endwhile;
else:
get_template_part('template-parts/property', 'none');
endif;
?>
Which is making my function not work. There is only 1 line of code in the template-parts/property-none and its just saying the same thing the other files are. So I'm not sure why the other template would not add the body class.
You can do like this example,
<?php
add_filter( 'body_class', 'custom_class' );
function custom_class( $classes ) {
if ( is_single('post') ) {
$classes[] = 'SearchBar';
}else{
$classes[] = 'noSearchBar';
}
return $classes;
}
?>
The following example will work for single post page. For more conditions.visit
Hope this will helps you.

Set Previous and next for the posts in wordpress

<?php
$args = array( 'numberposts' => '1' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<h1>' .$recent["post_title"].' </h1> ';
}
?>
I added this code for getting just single latest post on desired page.
How can I add next and previous button of posts to it?
If you want to get previous post link, You can do it using following code:
<?php $prev_post = get_adjacent_post( false, '', true ); ?>
<?php if ( is_a( $prev_post, 'WP_Post' ) ) { ?>
<?php echo get_the_title( $prev_post->ID ); ?>
<?php } ?>
If you want to get next post link, Than:
<?php $next_post = get_adjacent_post( false, '', false ); ?>
<?php if ( is_a( $next_post, 'WP_Post' ) ) { ?>
<?php echo get_the_title( $next_post->ID ); ?>
<?php } ?>
You can check more information about this function here : get_adjacent_post()
$previous=$recent["ID"]-1;
echo '' . PREVIOUS.' ';
$next=$recent["ID"]+1;
echo '' . NEXT.' ';
I did this and it worked :)

How to substring element inside html

I need to shorten the title in the previous and next buttons in a WP theme.
Here's the code:
<?php
/* ----------------------------------------------------------------------------------
Display navigation to next/previous pages when applicable.
---------------------------------------------------------------------------------- */
if ( ! function_exists( 'thinkup_input_nav' ) ) :
function thinkup_input_nav( $nav_id ) {
global $wp_query, $post;
// Don't print empty markup on single pages if there's nowhere to navigate.
if ( is_single() ) {
$previous = ( is_attachment() ) ? get_post( $post->post_parent ) : get_adjacent_post( false, '', true );
$next = get_adjacent_post( false, '', false );
if ( ! $next && ! $previous )
return;
}
// Don't print empty markup in archives if there's only one page.
if ( $wp_query->max_num_pages < 2 && ( is_home() || is_archive() || is_search() ) )
return;
?>
<nav role="navigation" id="<?php echo $nav_id; ?>">
<?php if ( is_single() ) : ?>
<?php previous_post_link( '<div class="nav-previous">%link</div>', '<span class="meta-icon"><i class="icon-angle-left icon-large"></i></span><span class="meta-nav">%title</span>' ); ?>
<?php next_post_link( '<div class="nav-next">%link</div>', '<span class="meta-nav">%title</span><span class="meta-icon"><i class="icon-angle-right icon-large"></i></span>' ); ?>
<?php elseif ( $wp_query->max_num_pages > 1 && ( is_home() || is_archive() || is_search() ) ) : // navigation links for home, archive, and search pages ?>
<?php if ( get_next_posts_link() ) : ?>
<div class="nav-previous"><?php next_posts_link( __( 'Older posts', 'lan-thinkupthemes') ); ?></div>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<div class="nav-next"><?php previous_posts_link( __( 'Newer posts', 'lan-thinkupthemes') ); ?></div>
<?php endif; ?>
<?php endif; ?>
</nav><!-- #<?php echo $nav_id; ?> -->
<?php
}
endif;
/* ----------------------------------------------------------------------------------
Display navigation to next/previous image when applicable.
---------------------------------------------------------------------------------- */
if ( ! function_exists( 'thinkup_input_imagesnav' ) ) :
function thinkup_input_imagesnav() {
global $wp_query, $post;
?>
<nav role="navigation" id="nav-below">
<div class="nav-previous"><?php previous_image_link( 'false', '<div class="nav-previous"><span class="meta-icon"><i class="icon-angle-left icon-large"></i></span><span class="meta-nav">' . __( 'Previous', 'lan-thinkupthemes') . ' </span></div>' ); ?></div>
<div class="nav-next"><?php next_image_link( 'false', '<span class="meta-nav">' . __( 'Next', 'lan-thinkupthemes') . '</span><span class="meta-icon"><i class="icon-angle-right icon-large"></i></span>' ); ?></div>
</nav><!-- #image-navigation -->
<?php
}
endif;
/* Display comments at bottom of post, page and project pages. */
function thinkup_input_allowcomments() {
if ( comments_open() || '0' != get_comments_number() )
comments_template( '/comments.php', true );
}
/* ----------------------------------------------------------------------------------
Returns true if a blog has more than 1 category.
---------------------------------------------------------------------------------- */
function thinkup_input_categorizedblog() {
if ( false === ( $all_the_cool_cats = get_transient( 'all_the_cool_cats' ) ) ) {
// Create an array of all the categories that are attached to posts
$all_the_cool_cats = get_categories( array(
'hide_empty' => 1,
) );
// Count the number of categories that are attached to the posts
$all_the_cool_cats = count( $all_the_cool_cats );
set_transient( 'all_the_cool_cats', $all_the_cool_cats );
}
if ( '1' != $all_the_cool_cats ) {
return true;
} else {
return false;
}
}
/* Flush out the transients used in thinkup_input_categorizedblog. */
function thinkup_input_transient_flusher() {
delete_transient( 'all_the_cool_cats' );
}
add_action( 'edit_category', 'thinkup_input_transient_flusher' );
add_action( 'save_post', 'thinkup_input_transient_flusher' );
What I tried was to add substring to this line:
<?php previous_post_link( '<div class="nav-previous">%link</div>', '<span class="meta-icon"><i class="icon-angle-left icon-large"></i></span><span class="meta-nav">%title</span>' ); ?>
to:
<?php previous_post_link( '<div class="nav-previous">%link</div>', '<span class="meta-icon"><i class="icon-angle-left icon-large"></i></span><span class="meta-nav"><?php echo substr(%title,0,10)?></span>' ); ?>
but upon reloading the page it displayed an empty text instead.
What am I doing wrong?
You can override the previous_post_link() function in your functions.php file of your theme as like this :
function previous_post_link($format='« %link', $link='%title', $in_same_cat = false, $excluded_categories = '',$limit = -1) {
if ( is_attachment() )
$post = & get_post($GLOBALS['post']->post_parent);
else
$post = get_previous_post($in_same_cat, $excluded_categories);
if ( !$post )
return;
$title = apply_filters('the_title', $post->post_title, $post);
if ($limit>-1) {$title = substr($title,0,$limit).'…';}
$string = '<a href="'.get_permalink($post->ID).'">';
$link = str_replace('%title', $title, $link);
$link = $pre . $string . $link . '</a>';
$format = str_replace('%link', $link, $format);
echo $format;
And then you can call the function with the additional argument to define your desired trim length:
<li><?php previous_post_link('%link','&laquo %title',FALSE,'',20); ?></li>
Hope it helps you.
Taken from https://wordpress.org/support/topic/using-substr-to-limit-characters-in-post-title

Trying to get property of non object

I am trying to code a function for Wordpress Post navigation but i am getting
Trying to get property of non object
error in lines with $prevpost->ID and $nextpost->ID, the code is this:
if ( ! function_exists( 'mm_post_nav' ) ) :
/**
* Displays navigation to next/previous post when applicable.
*
* #since 1.0
*
* #return void
*/
function mm_post_nav() {
global $post;
// Don't print empty markup if there's nowhere to navigate.
$previous = ( is_attachment() ) ? get_post( $post->post_parent ) : get_adjacent_post( false, '', true );
$next = get_adjacent_post( false, '', false );
$prevpost = get_previous_post(true);
$prevThumbnail = get_the_post_thumbnail($prevpost->ID, array(44,44) );
$nextpost = get_next_post(true);
$nextThumbnail = get_the_post_thumbnail($nextpost->ID, array(44,44) );
if ( ! $next && ! $previous )
return;
?>
<nav class="mm-post-nav" role="navigation">
<h1 class="screen-reader-text"><?php _e( 'Post navigation', 'mm-cube' ); ?></h1>
<div class="mm-single-nav">
<div class="mm-prev-link">
<?php previous_post_link( '%link', _x( '<i class="icon-chevron-left"></i><span class="mm-prev-post-title"> %title</span>', 'Previous post link', 'mm-cube' ) ); ?>
</div>
<div class="mm-next-link">
<?php next_post_link( '%link', _x( '<span class="mm-next-post-title">%title</span><i class="icon-chevron-right"></i>' , 'Next post link', 'mm-cube' ) ); ?>
</div>
</div><!-- .nav-links -->
<div class="clear"></div>
</nav><!-- .navigation -->
<?php
}
endif;
Making a var_dump($prevpost) outputs this:
string(0) ""
You may try something like following, because $prevpost and $nextpost could return empty/null if there is no matching posts are available.
$prevpost = get_previous_post(true);
if (!empty( $prevpost )) {
$prevThumbnail = get_the_post_thumbnail($prevpost->ID, array(44,44) );
}
$nextpost = get_next_post(true);
if (!empty( $nextpost )) {
$nextThumbnail = get_the_post_thumbnail($nextpost->ID, array(44,44) );
}
Return Values (get_previous_post and get_next_post)
Post object if successful.
Null if global $post is not set.
Empty string if no corresponding post exists.
Read more on Codex about get_previous_post and get_next_post to know how they work and what they return on any condition.
Update: Check the function's arguments, you have used (in both previous and next):
previous_post_link( $format, $link, $in_same_cat = false, $excluded_terms = '', $taxonomy = 'category' );
You should use:
previous_post_link( '%link', _x( '<i class="icon-chevron-left"></i><span class="mm-prev-post-title">%title</span>', FALSE, 'mm-cube' ) );
Use same order for other function. Check more on Codex about previous_post_link and next_post_link

Categories