why is WordPress printing my array instead of just constructing it? - php

I am trying to apply a custom view to all the results of a visit to a taxonomy page, which involves wrapping the whole lot of results in some DOM boilerplate and then invoking the function to display each result as an element within that boilerplate. My strategy of choice was to step through each result, populated dynamically depending which taxonomy term has led them here, and fill a bucket with those results, then display each one appropriately.
In other words, I want the WordPress loop to tell me WHICH things to display, then my own iteration to decide HOW to display them. This seemed like a simple strategy, but loops like the following appear to be always displaying my entire bucket, although I am nowhere telling it to actually print that bucket. Narrowing it down to a minimal example I have the following, which still is printing out $bucket. What is going on?
$bucket = array();
while ( have_posts() ) {
the_post();
$bucket[]=the_meta(); // this is all printed to the screen. Why?
}

the_meta(); // this is all printed to the screen. Why?
Wordpress has this concept of the_{name of function} and get_the_{name of function}. For example, the_title and get_the_title. the_title will echo out the title into the page but get_the_title will return the title instead.
the_{name of function} will echo out the result.
get_the_{name of function}, on the other hand, will return the result.
Read more on that
If you need to return the result instead of echoing it out into the page then use this version of the function: get_the_{name of function}.
So you could use the following code:
$bucket = array();
while ( have_posts() ) {
the_post();
$bucket[]=get_post_meta(get_the_ID());
}

Related

exclude posts without content from search result

I have search.php in my WordPress theme, search result is generating fine using The Loop.
What I see is some post don't have content(blank post with title only), and they still appear in search result. Which is quite obvious, but I want only to list post which has some content.
If post don't have any content it should not list in Search Result even if its title has a Search Term.
I believe you won't need to see code to understand my concern. I tried searching for this answer on all known resources, nothing found exactly.
Down vote won't help me.
Inside your search loop try adding this:
global $post;
if ( $post->post_content != '' ) {
// Display this post because it has content.
} else {
// This post has empty content so do not display it.
}

Wordpress PHP How to Get a Function's Return Value Into an If() Statemente

I'm trying to create and if() statement that works in accordance to the kind of post (i.e., page or article) and, if page, the title of such page.
The type of post can be obtained from its class function post_class() and the title from its title function the_title().
So I know where I can get the info I need but, then, no matter what, I cannot turn this info into a string I can test. Wherever I put any of these two functions I get an output onto the page.
First, I tried:
if(strpos(post_class(), 'page')) {
//DO SOMETHING
}
Didn't work. Just had the post_class() dumped onto the page.
Then, I tried calling the function as the value of a variable:
$this_class = post_class();
And had the same result.
I've since tried a couple of other dirtier ways of doing it but to no avail. It seems wherever these WP functions are placed, they will dump their values onto the page.
Perhaps somebody out there knows how I can successfully get the type of post and title and set them to if() statements in order to trigger whatever else.
Thanks!
According to Wordpress Docs:
post_class()
When the post_class function is added to a tag within the loop, for
example >, it will print out and add
various post-related classes to the div tag.
In case you would like to be able to retrieve the value you should use
the get_post_class() function which returns that value.
Retrieve the classes for the post div as an array.

retrieve query outside the wordpress loop with ajax.load in #content

I am working on an advanced search on wordpress based on custom taxonomies.
I'm stuck since 48h so I was hoping to have some help or thought...
Step 1 --- in the js file the query strings are created like that:
if (jQuery('#s').val() == ''){
URL = "/?genre=" + genre + '...other Stuff' #content';
}else{
URL = "/?s="+searchQueryString+"&genre=" + genre +'...other stuff' #content';
}
It nicelly load my custom loop in my #content div without changing the browser url or reloading the header, which is pretty good...so far. :-)
Step 2 --- then I wrote 2 functions in my function.php , one to load the loop with the GET[] elements on main page, using new WP_Query
and one that does the same thing for search queries:
add_action('pre_get_posts','SearchFilter');
Which is compiling my GET[] filters with the GET[s] in the content.php,
Still all good....
Step 3 --- (problem^^)---
I want to add a css class to desactivate the radio buttons located in my header.php, depending on the results in the loop.
Try-1 I thought I could create a php array to compile the terms found while the loop is happening, and then compare it with my buttons value.like that:
$args = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'slugs');
$results = wp_get_post_terms(get_the_ID(),'category',$args);
foreach ($results as $result){
array_push($stack, $result);
}
But there is no way to retrieve the data from that array in the header afterwhile, or to create it from the header using things like global $post;since my url doesn't change.
it just shows the homepage query.
Try-2 I also thought I could encode it to json and then put some action in my js file. but so far it just return json unexpected character, and I got the feeling that even if I crack it, its not going to be the right way since its going to make the js file heavier.
May be I'm just missing something about the Global wp_query and I don't need to charge my script?
Excuse my english and the long question,
thanks a lot in advance if you have an idea,
DACO
I'm going to use wp_localize_script to export the array to my js script,
Thanks sorted

Wordpress: Inserting if-else statement into next_post_link() / previous_post_link() parameters?

First question here, though reading and searching has saved my bacon a number of times.
I'm a PHP hack at best, and a Wordpress theme I'm building is forcing me to learn a lot.
I've run into a problem in trying to get the next & previous links' formats to display differently based on their respective categories (and not the single.php's page).
Here's my best try so far:
<?php next_post_link(
'%link',
if ( in_category( 'tweet' ) ) {
get_the_content()
} else {
echo '%title'
};,
FALSE
)?>
This results in a syntax error.
My first question is can I even use an if-else statement within a function's parameters?
If I'm approaching it in completely the wrong way, then it's back to the drawing board. I'd appreciate any alternate suggestions, then, as well!
I know the following work:
next_post_link( '%link', get_the_title(), FALSE );
next_post_link( '%link', '%title', FALSE );
To try and be more clear, I'm looking to affect output of the next/previous links based on the category of the links themselves, and not the present host page they are on.
The problem I'm having is a) how to determine what category the next_post_link() and previous_post_link() are, and then b) display their Link parameter accordingly. If I may throw up the white flag, the examples I've found using get_adjacent_post() and various arrays and the like seem way over my head at this point. I'd really appreciate someone walking me through any solutions using them.
What to aim for?
I think you're mixing stuff a bit too much which makes your problem more complicated than it needs to be. I know with many new things, this can happen quite easily, so I think it's worth to spend some thoughts about the what to be done before starting to code. It should help in the end.
Start to formulate what you want to achieve. If I understand you right you write that you want to display the next and prev links below the current post differently based on category.
But which category? The one of the current post that displays? Or the category of the prev/next linked post?
Next to that, posts can have multiple categories. Do you want to change the display based on one or on multiple of or even all of the categories?
And finally: Do you want to output tons of HTML tags for the visual styling? Or do you want to use CSS for that.
How to do it?
After you have thought about what you actually want to achieve, you can make your mind how this can be done.
In the following I'll show some example code that will do the following:
Explains the use of the link-format parameter you want to change.
Shows how to get the CSS-classes for the links in question.
Extends a theme's output with these CSS-classes.
Make it re-useable for different files within your theme.
So this example covers the categories of the linked posts for visual styling via your Theme's CSS which I think is the preferable way.
The PHP code
PHP is pretty flexible so it's in the end easy to get that done, but without knowing what exactly to do, this flexibility in PHP can turn out to be a problem because it's also possible to loose the trail and then code something non-working.
Let's just say you just want to change the link-format for the next_post_link() function.
The function will replace %link with the HTML link tag (<a href=...>Post Title</a>), so if you take 'This is the next post of my blog: %link; waiting to be read!' as parameter, you've added some text around the link.
<?php
$format = 'This is the next post of my blog: %link; waiting to be read!';
next_post_link($format);
?>
You can additionally add HTML tags around it as well:
<?php
$format = '<span style="font-size:2em">%link</span>';
next_post_link($format);
?>
Which will make all next post links having a double of their standard font-size.
So now to make this a bit more easy for themeing, best would be to add css classes of the category/ies then you can change the display easily within the CSS.
<?php
$inSameCategory = true; // depends on what you want, can be false as well
$nextPost = get_adjacent_post($inSameCategory, '', false);
$cssClasses = get_post_class('next-post-link ', $nextPost);
$format = sprintf('<span class="$s>%link</span>', $cssClasses);
next_post_link($format);
?>
This will wrap the next post link into a <span> containing all CSS-classes of the linked post plus a next-post-link class in case you need this for the CSS-selector to style the links. Here some example CSS:
.next-post-link.category-tweet {font-size: 2em;}
Making it reuseable
As you have a next and prev link you could copy over that code only for changing one parameter. But we're lazy and instead we wrap it into a function of it's own:
/**
* my theme's format string for prev|next_post_link()
*
* #param bool $previous (optional) previous (true, default) or next (false) post
* #param bool $inSameCategory (optional) use same category, default: true
* #return string
*/
function my_prev_next_link_format($previous = true, $inSameCategory = true) {
$postId = get_adjacent_post($inSameCategory, '', $previous);
$cssClasses = get_post_class('next-post-link ', $nextPost);
$format = sprintf('<span class="$s>%link</span>', $cssClasses);
return $format;
}
Place this function into your theme's functions.php. It's available then in all your templates. Using it becomes now very easy:
<?php prev_post_link(my_prev_next_link_format()); ?>
...
<?php next_post_link(my_prev_next_link_format(false)); ?>
If you've put this all together, you can easily style the next and prev links within your theme's CSS.
Have you tried anonymous functions? In that way you can use if-else statements within a function
Try:
$format_string = in_category('tweet') ?
'<span style="color:red;">%link</span>' : '%link';
next_post_link($format_string);
The second and third parameters are optional and default to title and false.
Edit:
I don't know this plugin, but..
if(in_category('tweet')){
$format_string = '<span style="color:red;">%link</span>';
$link_text = get_the_content();
}else{
$format_string = '%link';
$link_text = '%title';
}
next_post_link($format_string, $link_text);

Wordpress loop export category list to php echo

Am a bit stuck with a wordpress loop, am wondering if anyone can help.
I need to run a Wordpress loop but only get the category names/id (Either is fine) from each post and have all of those variables as one php item I can echo later in the page.
Its for a category list filter system, but I only want to show categories which have posted displayed on that page.
The loop will be dynamic as well, so I cant just hard code exclude/include, I need to echo the value of all the numbers in together.
I hope that makes sense! Anyone who has any ideas would be really cool. Thanks!
I would use the get_the_category function like so...
<?php
// before you begin the wordpress loop
$category_array = array();
?>
<?php
// from *within* the wordpress loop
foreach((get_the_category()) as $category) {
if (!in_array($category->cat_name, $category_array)) {
$category_array[] = $category->cat_name;
}
}
?>
<?php
// after the wordpress loop is finished
echo implode(",", $category_array);
?>
This code basically creates a new (empty) array so that for each category in the current page, check if you've already added that category name to the array, then if not, go ahead and add it. Then when the loop is finished, echo out a comma separated string of category names. (You can of course, change the separator if you want a comma and space ", " or any other delimiter).
The Codex article has a lot more information on other things you can do with that function. Hope that helps.
Edit: Fixed the implementation because I forgot this was going to be used on a page where you are listing many posts using the loop. (You need to initialize your array from outside the wordpress loop, then echo your results after the loop has been finished).

Categories