Enter the_loop() from posts ID - php

I have looked for this problem and I haven't seen it asked before. I'm sorry if this is a repeated question.
I have done a complex query to my custom database tables, and I have now an array of wordpress posts IDs.
Now I would like to show them with the_loop, but I'm not able to do that. I think it's important to advise you that I'm showing the results by ajax, so all this functionality is in functions.php (maybe this information is irrelevant).
For now I'm getting the posts data with:
function imprimirResultados($resultados = null){
if ($resultados){
echo '<div class="resultados">';
foreach ($resultados as $post_id){
$post = get_post( $post_id[0], ARRAY_A );
echo '<div class="post" id="post-'.$post['ID'].'">
<h2><a href="'.$post['guid'].'" rel="bookmark" title="Permanent Link to '.$post['post_name'].'">
'.$post['post_title'].'</a></h2>
<div class="entry">
'.$post['post_excerpt'].'
</div>
</div>';
}
echo '</div>';
var_dump($post);
}else{
echo '<h2 class="center">No encontrado</h2>
<p class="center">Lo sentimos, pero la búsqueda no obtuvo resultados.</p>';
}
}
But it is not a clean method to do that, and I can't use other functionalities that the objects generated by the_loop() already have.
--------------------------------- Edit -------------------------------
I leave here the functions I use:
function resultadosLigeros_callback(){
(...)
$querystr = cargar_ligeros($marca,$modelo,$combustible,$tipo,$anio); //This function generate a MySQL query
$resultados = $wpdb->get_results($querystr, ARRAY_N);
imprimirResultados($resultados, $querystr);//This function is the one I wrote before
die();
}

You'll want to generate a new WP_Query, based on the post IDs you have. Specifically, you'll want to use post__in.
For example, since $resultados is an array:
<?php
// Fetch the posts
$query = new WP_Query( array( 'post__in' => $resultados ) );
// The Loop
while ( $query->have_posts() ) : $query->the_post();
?>
You can then use functions such as the_ID(), etc., directly within your template logic.

Related

get_option intermittently fail WordPress

This is my first question.
I have a custom taxonomy set up in a theme inside a functions.php file.
I've added some extra meta fields for the custom taxonomy (category), also set through the functions.php file.
I am using the update_option() function.
Here is the part that is saving the options to the DB:
<?php
// save extra category extra fields hook
add_action ( 'edited_artists', 'save_extra_category_fileds');
// save extra category extra fields callback function
function save_extra_category_fileds( $term_id ) {
if ( isset( $_POST['Cat_meta'] ) ) {
$t_id = $term_id;
$cat_meta = get_option( "category_$t_id");
$cat_keys = array_keys($_POST['Cat_meta']);
foreach ($cat_keys as $key){
if (isset($_POST['Cat_meta'][$key])){
$cat_meta[$key] = $_POST['Cat_meta'][$key];
}
}
//save the option array
update_option( "category_$t_id", $cat_meta );
}
}
?>
In my template file I am calling them like this:
<?php
$terms = wp_get_post_terms( $post->ID, 'artists');
foreach ($terms as $term){
$term_id = $term->term_id;
$term_name = $term->name;
$term_taxonomy_id = $term->term_taxonomy_id;
$term_slug = $term->slug;
//do you term meta stuff here
//print_r($term);
}
?>
This is where I use them (among other things), and it is of course inside the LOOP:
<div class="single-sculpture-artist-info">
<?php
$category_meta = get_option( "category_$term_taxonomy_id");
?>
<a href="<?php echo get_site_url(); ?>/artists/<?php echo $term_slug; ?>">
<img src="<?php echo $category_meta['artists_photo'] ?>" alt="<?php echo $term_name; ?>">
</a>
<h3>
<?php echo $term_name; ?>
</h3>
<p><?php echo $category_meta['artists_city_province'] ?></p>
<p><?php echo $category_meta['artists_bio_excerpt'] ?></p>
</div>
All of this code works perfectly.
I started adding the content, but then it suddenly started to fail. I think it started when I tried to use one of the category (taxonomy) names I used while developing this whole system (my guess is that it was cached somewhere or something), but then I tried using it with different name, and adding some other which were not there before, and it fails as well. My best guess is that somehow the options table is overloaded with data (limit or something).
Is that even possible? I dont have a lot, 56 working posts in that taxonomy, and 34 categories(taxonomy terms).
I tried my best to get my head around it but couldn`t find what was the problem.
When I insert like 2 or 3 more posts, it starts messing around. So, this:
<a href="<?php echo get_site_url(); ?>/artists/<?php echo $term_slug; ?>">
outputs correct link, but, this:
<img src="<?php echo $category_meta['artists_photo'] ?>"
doesnt. It outputs data from some other category (from the same CPT). I can provide additional info upon request.
Not answering to your question but do you know there’s a big change happening with WP 4.2+ where they’re going to be splitting taxonomy terms, so that taxonomy terms don’t share the same term id if their slugs match.
Please take a look at the links below for some details on how this can be addressed
https://make.wordpress.org/core/2015/02/16/taxonomy-term-splitting-in-4-2-a-developer-guide/
https://developer.wordpress.org/plugins/taxonomy/working-with-split-terms-in-wp-4-2/
Through the help of my network I found the solution to the problem. The line where I am calling:
<?php
$category_meta = get_option( "category_$term_taxonomy_id");
?>
I switched to this:
<?php
$category_meta = get_option( "category_$term_id");
?>
This seems to have resolved the problem. However, here are some other solutions that might be more relevant in the similiar situation:
https://en.bainternet.info/tax-meta-class-faq/
also, be sure to read the things Joe Wilson posted above. Thanks again.

wordpress combine page and posts

I am creating a wp template based on 2013. I want to display a 'page' that has some content from a page and then 6 posts on it. These posts have been selected via the themes options panel using the settings api. So I can get at each one using
$options = get_option( 'osc_theme_options' );
The template i have been using so far is based on a page so i am guessing I need to change the loop in someway.
The loop goes:
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>...
I want to know how to alter the loop so that it pulls in just the posts that have been selected. At the moment this template/loop is only pulling in the page - which I guess is fair enough.
Would it be possible to create 'another loop' maybe under the first that then brings in the selected posts - if so how?
Many thanks
Yes you can effectively create another loop under the existing loop to display the posts. I am not sure what $options = get_option( 'osc_theme_options' ); returns, i.e an array of Post ID's etc. In order to show the posts you need to do a custom loop:
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() )
{
echo '<ul>';
while ( $the_query->have_posts() )
{
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
}
else
{
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
This is taken from:
https://css-tricks.com/snippets/wordpress/custom-loop-based-on-custom-fields/
Also see the following:
https://digwp.com/2011/05/loops/
http://www.smashingmagazine.com/2013/01/14/using-wp_query-wordpress/
So effectively it all boils down to the $args variable as to which posts you will get. Here is an example of multiple ids
id=2,6,17,38
So if $options = get_option( 'osc_theme_options' ); returns an array of post ids like so:
array(
0=>1
1=>22
2=>27
)
You could probably do something like:
$args = "id=".implode($options,",");
This is the best advice I can give without deeper knowledge of the theme etc.

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.

How can I get all records of taxonomy category in WordPress Query?

I have use easy content Types plugin & created Post type in WP call Recipes. I have also added a taxonomy category in it & created 4 categories like Starter, Drinks, etc etc.
Now in WP query I need to get all records of starter.
So how can I get that?
I am using this query, but it is not working. It is giving all records of Recipes post type
Here is Query
$recipes = query_posts('post_type=recipes&taxonomy=recipescategory&category_name=Starters');
You have a lot of errors in your code and a misunderstanding about categories.
Never use query_posts to construct a custom query
Note: This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination)
If you have to run a custom query, make use of WP_Query or get_posts
category_name takes the category slug, not the name. The parameter's name is deceiving
The "categories" belonging to a custom taxonomy are called terms. I have written a post which I have also included in the codex which you can check here, it describes the differences.
To retrieve posts from a custom taxonomy, you need to make use of a tax_query. The category parameters will not work here
With all the above said, create your query so that it looks like this
$args = array(
'post_type' => 'recipes',
'tax_query' => array(
array(
'taxonomy' => 'recipescategory',
'field' => 'name',
'terms' => 'Starters',
),
),
);
$query = new WP_Query( $args );
if( $query->have_posts() ){
while( $query->have_posts() ) {
$query->the_post();
//Your loop elements
}
wp_reset_postdata();
}
try it
$ar = array (
'post_type'=>'recipes',
'taxonomy'=>'recipescategory',
'category_name'=>'Starters'
);
$posts = get_posts($ar);
** foreach loop**
foreach($posts as $p){ ?>
<div class="sub_cont">
<div class="sub_img">
<?php $url = wp_get_attachment_url( get_post_thumbnail_id($p->ID));?>
<img src="<?php echo $url; ?>" longdesc="URL_2" alt="Text_2" />
</div>
<div class="desc_title">
<a href="<?php echo $permalink = get_permalink( $p->ID); ?>">
<?php echo $post_title=$p->post_title; ?>
</a>
</div>
<div class="cont_add"></div>
</div>
<?php } ?>
You can use get_posts function
$args = array("post_type"=>"recipes","category_name"=>"starter","posts_per_page"=>20);
$starters = get_posts($args);

Find all Wordpress posts that contain a certain word

Without adding any tags or categories, I need a way to generate a page that lists all Wordpress posts containing the word, for example, "design" somewhere within them. Does anyone know how to do this?
You can use WP_Query to do a search:
<?php
$query = new WP_Query( 's=keyword' );
if ($query->have_posts()){
while ( $query->have_posts() ) { $query->the_post();
echo '<h2>';
the_title();
echo '</h2>';
the_content();
} //end while
}
Let me know how it went!

Categories