Wordpress ajax search get post category - php

I'm using a wp theme which comes with an ajax search feature to get live suggestions. However the suggestion element displays the post type (under the resulted title) such as "Portfolio item" and I would like to replace it with the post (portfolio item's) category. Any solution? Thanks in advance!
$suggestions=array();
global $post;
foreach ($posts as $post): setup_postdata($post);
// Initialise suggestion array
$suggestion = array();
$suggestion['label'] = esc_html($post->post_title);
$suggestion['link'] = get_permalink();
$suggestion['image'] = (has_post_thumbnail( $post->ID )) ? get_the_post_thumbnail($post->ID, 'thumbnail', array('title' => '')) : '<i class="icon-salient-pencil"></i>' ;
if(get_post_type($post->ID) == 'post'){
$suggestion['post_type'] = __('Story',NECTAR_THEME_NAME);
} else if(get_post_type($post->ID) == 'page'){
$suggestion['post_type'] = __('Page',NECTAR_THEME_NAME);
} else if(get_post_type($post->ID) == 'portfolio'){
$suggestion['post_type'] = __('Portfolio item',NECTAR_THEME_NAME);
//show custom thumbnail if in use
$custom_thumbnail = get_post_meta($post->ID, '_nectar_portfolio_custom_thumbnail', true);
if(!empty($custom_thumbnail) ){
$attachment_id = pn_get_attachment_id_from_url($custom_thumbnail);
$suggestion['image'] = wp_get_attachment_image($attachment_id,'portfolio-widget');
}
} else if(get_post_type($post->ID) == 'product'){
$suggestion['post_type'] = __('Product',NECTAR_THEME_NAME);
}

Related

How can I display the page category name, not just the post category name?

This code displays the post category name, but I need to display the page category name as well. What do I need to change in this code? I am using "Create And Assign Categories For Pages" plugin.
<?php if ('post' == get_post_type($post->ID) && rehub_option('exclude_cat_meta') != 1) :?>
<?php $category = get_the_category($post->ID); ?>
<?php if ($category) {
if ( class_exists( 'WPSEO_Primary_Term' ) ) {
$wpseo_primary_term = new WPSEO_Primary_Term( 'category', $post->ID );
$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
if (!is_numeric($wpseo_primary_term )) {
$first_cat = $category[0]->term_id;
}else{
$first_cat = $wpseo_primary_term;
}
}else{
$first_cat = $category[0]->term_id;
}
meta_small( false, $first_cat, false, false );
} endif; ?>

Adding class for only 1st element of array of custom field with same values in php

I have custom field with key Slider Image for a page in WordPress. This key accepts multiple values. admin dashboard for the page
Here's the php code for displaying the aforesaid in the front-end:
$slider_image = get_post_meta($post->ID, 'Slider Image', false);
if( count( $slider_image ) != 0 ) {
foreach($slider_image) {
echo '<li class="">...</li>';
}
}
This outputs the expected
<li class="">...</li>
<li class="">...</li>
<li class="">...</li>
.
.
.
I want only the 1st li to have class of active. How can I do this? This, I think, comes close to the answer.
You can do it in two ways, either by PHP with the following approch
if(count($slider_image)!= 0) {
$flag = 1;
foreach($slider_image as $img) {
if($flag==1) {
echo '<li class="active">...</li>';
$flag++;
}
else {
echo '<li class="">...</li>';
}
}
}
or using jQuery using the following way
$('#parentID li:first').addClass('aaaa');
where parentID is is the id of the parent element of the li elements.
Use a for loop instead if it's number index:
if( false != ($len = count( $slider_image ))) {
for($i=0;$i<$len;$i++){
//$value = $slider_image[$i];
$class = $i==0 ? 'active' : '';
echo '<li class="'.$class.'">...</li>';
}
}
If it's not you can do this with foreach
$slider_image = get_post_meta($post->ID, 'Slider Image', false);
if( count( $slider_image ) != 0 ) {
$first = key($slider_image); //get the key at the current position (the first one)
foreach($slider_image as $key=>$value) {
$class = $key==$first ? 'active' : '';
echo '<li class="'.$class.'">...</li>';
}
}
If you want to get fancy you could do a do/while loop like this:
$slider_image = get_post_meta($post->ID, 'Slider Image', false);
if( count( $slider_image ) != 0 ) {
do{
$class = !isset($class) ? 'active' : '';
//$value = current($slider_image);
echo '<li class="'.$class.'">...</li>';
next($slider_image);
}while(current($slider_image));
}
Simple.
$slider_image = get_post_meta($post->ID, 'Slider Image', false);
if( is_array( $slider_image ) )
{
$cls = 'active';
foreach($slider_image as $img)
{
echo '<li class="' . $cls . '">...</li>';
$cls = '';
}
}
Even better you do it in PHP style as embedded language:
if( is_array( $slider_image ) )
{
$cls = 'active';
foreach($slider_image as $img)
{
?>
<li class="<?php echo $cls;?>"><img src="<?php echo $img?>"></li>
<?php
$cls = '';
}
}
However, if you need this class in JavaScript, I would set it also in JavaScript before slider initialization.
if(!document.querySelector('ul#mylist>li.active'))
document.querySelector('ul#mylist>li:first-child').classList.add('active');

Notice: is_main_query was called incorrectly

Was searching for two days what makes problem in my WordPress theme, and using debug I found this error, and that what I have in functions about that error code.
It displays notice on place where section box should be shown.
How can I fix this?
Notice: is_main_query was called incorrectly. In pre_get_posts, use the WP_Query->is_main_query() method,
// Filter to "pre_get_posts" to change query vars
add_action( 'pre_get_posts', 'dp_custom_get_posts' );
function dp_custom_get_posts( $query ) {
if(is_admin())
return;
$orderby = $query->get('orderby');
$order = $query->get('order');
// If no 'orderby' specified, get first sort type from selected sort types
$selected_sort_types = dp_selected_sort_types();
if(is_main_query() && !empty($selected_sort_types) && empty($orderby)) {
$_sort_types = array_keys($selected_sort_types);
$orderby = $_sort_types[0];
$query->set('orderby', $orderby);
}
// Reset query vars based orderby parameter
if($orderby == 'comments') {
$query->set('orderby', 'comment_count');
}
elseif($orderby == 'views') {
$query->set('orderby', 'meta_value_num');
$query->set('meta_key', 'views');
// The arguments for BAW Post Views Count plugin
if(function_exists('baw_pvc_main')) {
global $timings;
$views_timing = $query->get('views_timing') ? $query->get('views_timing') : 'all';
$date = $views_timing == 'all' ? '' : '-'. date( $timings[$views_timing] );
$meta_key = apply_filters( 'baw_count_views_meta_key', '_count-views_' . $views_timing . $date, $views_timing, $date );
$query->set('meta_key', $meta_key);
}
}
elseif($orderby == 'likes') {
$query->set('orderby', 'meta_value_num');
$query->set('meta_key', 'likes');
}
elseif($orderby == 'title' && !$order) {
// If order by title, and no order specified, set "ASC" as default order.
$query->set('order', 'ASC');
}
// Only display posts on search results page
if (is_search() && $query->is_main_query())
$query->set('post_type', 'post');
// Make tax_query support "post-format-standard"
$tax_query = $query->get('tax_query');
if(!empty($tax_query)) {
foreach($tax_query as $index => $single_tax_query) {
if(empty($single_tax_query['terms']))
continue;
$in_post_formats = (array)$single_tax_query['terms'];
if($single_tax_query['taxonomy'] == 'post_format'
&& $single_tax_query['field'] == 'slug'
&& in_array('post-format-standard', $in_post_formats)) {
// Get reverse operator
$reverse_operator = 'IN';
if(empty($single_tax_query['operator']) || $single_tax_query['operator'] == 'IN')
$reverse_operator = 'NOT IN';
elseif($single_tax_query['operator'] == 'AND')
break;
// Get "not in post formats"
$post_formats = get_theme_support('post-formats');
$all_post_formats = array();
if(is_array( $post_formats[0])) {
$all_post_formats = array();
foreach($post_formats[0] as $post_format)
$all_post_formats[] = 'post-format-'.$post_format;
}
$not_in_post_formats = array_diff($all_post_formats, $in_post_formats);
// Reset post_format in tax_query
$query->query_vars['tax_query'][$index] = array(
'taxonomy' => 'post_format',
'field' => 'slug',
'terms' => $not_in_post_formats,
'operator' => $reverse_operator
);
}
}
}
return $query;
}
This is the code of an section box, or at least part of it, I'm not sure what I'm doing anymore:
function dp_section_box($args = array()) {
$defaults = array(
'post_type' => 'post',
'cat' => '',
'taxonomies' => array(),
'view' => 'grid-small',
'title' => '',
'link' => '',
'post__in' => '',
'posts_per_page' => '',
'hide_if_empty' => false
);
$args = wp_parse_args($args, $defaults);
extract($args);
$posts_per_page = absint($posts_per_page);
// Set default posts number if no specified
if(empty($posts_per_page)) {
if($view == 'grid-mini')
$posts_per_page = 8;
elseif($view == 'grid-small')
$posts_per_page = 6;
elseif($view == 'grid-medium')
$posts_per_page = 4;
elseif($view == 'list-small')
$posts_per_page = 3;
elseif($view == 'list-medium')
$posts_per_page = 2;
elseif($view == 'list-large')
$posts_per_page = 1;
}
$args['posts_per_page'] = $posts_per_page;
$args = dp_parse_query_args($args);
$query = new WP_Query($args);
// Output nothing if there is no posts
if(!$query->have_posts() && $hide_if_empty)
return;
// Output content before section
if(!empty($before))
echo '<div class="section-box section-before rich-content">'. do_shortcode(wp_kses_stripslashes($before)).'</div><!-- end .section-box -->';
// Section box begin
echo '<div class="section-box">';
global $section_view;
$section_view = $view;
// Get term name as title
$term = '';
$cat = '';
if(!empty($taxonomies['category']))
$cat = $taxonomies['category'];
if($cat)
$term = get_term($cat, 'category');
if(empty($title) && $term)
$title = $term->name;
if(empty($link) && $term)
$link = get_term_link($term, 'category');
$title = '<span class="name">'.$title.'</span>';
// Add link to title and more
$more = '';
if($link) {
$title = '<a class="name-link" href="'.$link.'">'.$title.'</a>';
$more = '<a class="more-link" href="'.$link.'"><span>'.__('More', 'dp').' <i class="mini-arrow-right"></i></span></a>';
}
// Output section header
echo '<div class="section-header"><h2 class="section-title">'.$title.'</h2>'.$more.'</div>';
// Output section content
echo '<div class="section-content '.$view.'"><div class="nag cf">';
while ($query->have_posts()) : $query->the_post();
get_template_part('item-video');
endwhile;
wp_reset_postdata();
echo '</div></div><!-- end .section-content -->';
the solution is given in your error itself "use the WP_Query->is_main_query() method"-
try this -
if($query->is_main_query() && !empty($selected_sort_types) && empty($orderby)) {
$_sort_types = array_keys($selected_sort_types);
$orderby = $_sort_types[0];
$query->set('orderby', $orderby);
}
instead of this -
if(is_main_query() && !empty($selected_sort_types) && empty($orderby)) {
$_sort_types = array_keys($selected_sort_types);
$orderby = $_sort_types[0];
$query->set('orderby', $orderby);
}

Image upload to wordpress

So, I have the following to add an image in the wordpress post:
<?php
global $current_user;
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
if (isset ($_POST['title'])) {
$title = $_POST['title'];
} else {
echo 'Please enter a title';
}
if (isset ($_POST['description'])) {
$description = $_POST['description'];
} else {
echo 'Please enter the content';
}
$tags = $_POST['post_tags'];
$custom_field_1 = $_POST['custom_1'];
$custom_field_2 = $_POST['custom_2'];
$post = array(
'post_title' => $title,
'post_content' => $description,
'post_category' => $_POST['cat'],
'tags_input' => $tags,
'post_status' => 'publish',
'post_type' => $_POST['post_type']
);
$pid = wp_insert_post($post);
add_post_meta($pid, 'rh_content', $custom_field_1, true);
add_post_meta($pid, 'rh_item', $custom_field_2, true);
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
}
}
wp_redirect( home_url() );
}
do_action('wp_insert_post', 'wp_insert_post');
?>
So, it allows an image to be uploaded which can be shown by get_the_post_thumbnail.
<?php if ( has_post_thumbnail() ) { ?>
<div class="rhmi_thumb">
<?php if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'rh_site') ?>
</div>
<?php } ?>
However, even without the image uploaded (ie. there is no thumbnail), it still shows class="rhmi_thumb". So, I am guessing that the whether an image is uploaded or not, the post thinks that there is a thumbnail.
What modification should be made in the post upload form?
Thanks
For uploading image into page/post you have to use wp_insert_attachment(). I have added the link of wordpress site from there you can get the example that how you can implement that. Thanks!

Image Caption with the_post_thumbnail in WordPress

Is there a way to display the image caption where ever available when displaying the_post_thumbnail() image in WordPress on the posts in the primary loop.
Thanks! Appreciate all the help.
Here is an easier and shorter code :
<?php the_post_thumbnail();
echo get_post(get_post_thumbnail_id())->post_excerpt; ?>
As of WordPress 4.6, the function the_post_thumbnail_caption() has been added to core (/wp-includes/post-thumbnail-template.php).
Using the code posted here will cause the error:
Fatal error: Cannot redeclare the_post_thumbnail_caption()
I figured it out:
/************************************************************\
* Fetch The Post Thumbnail Caption
\************************************************************/
function the_post_thumbnail_caption() {
global $post;
$thumbnail_id = get_post_thumbnail_id($post->ID);
$thumbnail_image = get_posts(array('p' => $thumbnail_id, 'post_type' => 'attachment'));
if ($thumbnail_image && isset($thumbnail_image[0])) {
echo $thumbnail_image[0]->post_excerpt;
}
}
if(!function_exists('get_post_thumbnail_caption')) {
function get_post_thumbnail_caption($post_id = null) {
$post_id = ( null === $post_id ) ? get_the_ID() : $post_id;
$thumbnail_id = get_post_thumbnail_id($post_id);
if ($thumbnail = get_post($thumbnail_id))
return $thumbnail->post_excerpt;
return '';
}
}
if(!function_exists('the_post_thumbnail_caption')) {
function the_post_thumbnail_caption($post_id = null) {
echo get_post_thumbnail_caption($post_id);
}
}
if(has_post_thumbnail()) {
the_post_thumbnail();
the_post_thumbnail_caption();
$caption = get_post_thumbnail_caption(123);
if('' == $caption)
echo '<div class="caption">'.$caption.'</div>';
}

Categories