This is my first question here, hope to be useful in future to someone. We work on a WordPress site now, and try to display meta description content generated by All In One Seo plugin outside the loop. It's not a problem when it's on page/post. The code that works for single is
<?php $metadesc = get_post_meta($post->ID, '_aioseop_description', true);
if ($metadesc) {
echo $metadesc;
} else {
the_excerpt();
}
?>
Later on the other day I came with this solution
<?php $mykey_values = get_post_custom_values('_aioseop_description');
foreach ( $mykey_values as $key => $value ) {
echo "$value";
} ?>
I'm not sure if it's good to use this one, the problem I have now is that I want to display exact number of symbols, not all the content.
Well it was pretty lame question, but sometimes when you are stuck it's hard to see simple things. This is my final code which do the work for me:
<?php $mykey_values = get_post_custom_values('_aioseop_description');
foreach ( $mykey_values as $key => $value ) {
echo substr("$value",0 ,150); //This will display the first 150 symbols
} ?>
Related
I need creating custom multiple loops for my blog home.php in order to show 3 different content layout of defined category then proceed with the general loop excluding posts ID within the first 3 loops.
So far I made the the 3 different content layout of defined category category_name=arts:
<?php $posts = get_posts('numberposts=1&offset=0'); foreach ($posts as $post) : start_wp(); ?>
<?php static $count1 = 0; if ($count1 == "1") { break; } else { ?>
<?php the_title(); ?>
<?php $count1++; } ?>
<?php endforeach; ?>
<?php query_posts('category_name=arts&showposts=1'); ?>
<?php $posts = get_posts('numberposts=1&offset=1'); foreach ($posts as $post) : start_wp(); ?>
<?php static $count2 = 0; if ($count2 == "1") { break; } else { ?>
<?php the_title(); ?>
<?php $count2++; } ?>
<?php endforeach; ?>
<?php query_posts('category_name=arts&showposts=1'); ?>
<?php $posts = get_posts('numberposts=1&offset=2'); foreach ($posts as $post) : start_wp(); ?>
<?php static $count3 = 0; if ($count3 == "1") { break; } else { ?>
<?php the_title(); ?>
<?php $count3++; } ?>
<?php endforeach; ?>
I did get stuck to proceed with the general loop. Any suggestions are much appreciated.
You have serious issues here
For each loop you are running two queries, one withget_posts() and one with query_posts
You are making use of query_posts which you should never ever use. This adds a huge overhead on your query as you rerun the main query, so you are actually running 3 queries to get 1 post for each loop. This slows your page down which costs you dearly when it comes to SEO
Furthermore, query_posts breaks the main query object which breaks thousands of functions an plugins that relies on the main query object. You should really spent time and read this post on just how really bad query_posts is.
start_wp() was already depreciated in WordPress version 1.5. This means your code has bugs, and one should avoid bugs at all costs. You should really turn on debug while developing as debug will immediately throw a debugging message telling you that you are using a depreciated function. Here is an article from the codex on how to work with the debugging feature in WordPress. You should be using setup_postdata( $post )
Still on the debugging part, showposts was dropped in favor of posts_per_page
You are running a foreach loop without making sure you have posts to display. ALWAYS ALWAYS make sure you have valid values before you try to do anything with a dynamic variable. This will avoid numerous bugs should your variable return an empty value.
You should really work on your formatting as your code is quite hard to read when everything is packed into one line. Use proper indentation. Properly indented and formatted code does help a lot with readability and debugging. Also, drop the : and endforeach syntax. Although it is valid, it is not supported by code editors which make debugging a nightmare should your code fail. I always tell everyone to use the old style curly brackets as all code editors support them. They make debugging very easy
ALWAY ALWAYS, VERY IMPORTANT, always reset custom queries. Use wp_reset_postdata() to reset the $post global whenever you call setup_postdata() or the_post() in a custom query. Just for interest, because I have already stated to never use query_posts, you should use wp_reset_postdata() to reset custom queries created with query_posts
Lastly, you can do what you need with the specified category in only one loop, not three. Simply make use of your counters. If this is purely for styling, you can simply use the :nth child() selector in css3
The following is untested, but you can try the following
$special_cat_args = [
'category_name' => 'art',
'posts_per_page' => 3,
//Add extra arguments here
];
$art_posts = get_posts( $special_cat_args );
// Setup a variable to store the post ID's so we can exclude them in the 'main' query
$ids_array = [];
// Check if we have posts before we continue
if ( $art_posts ) {
// Start our counter
$counter = 0;
// Start the loop
foreach ( $art_posts as $post ) {
// Setup postdata, must use $post
setup_postdata( $post );
// Store the post id in an array to exclude in "main" query
$ids_array[] = $post->ID;
// Do something separate for every post
if ( 0 == $counter ) {
// Do something for post one
} elseif ( 1 == $counter ) {
// Do something for post two
} elseif ( 2 == $counter ) {
// Do something for post three
}
// Update the counter
$counter++;
} //endforeach $art_posts
wp_reset_postdata(); // VERY VERY IMPORTANT
} //endif $art_posts
// Now we can do our "main" query and exclude the three posts from the special category
$args = [
'post__not_in' => $ids_array, // Exclude the three post from previous query
// Rest of your arguments
];
$q = get_posts( $args );
// Run your loop
I've tried, believe me I've tried to figure this out but for the best part of the day it has beaten me so I have to ask this question:
I have a list ($list) of 100 words which I have put into an array:
foreach ($tag_array as $key => $names ) {
Each of these names I want to be a variable which I can use to assign some html for output within a html eg:
$arrayitem6 = 'whatever';
print $arrayitem6;
The reason I want to do this is because the 100 items in the list actually turns into 400 items in a html page which I would have to manually write out into a huge long repeating block of html. I want to create a single block of html/code using the array list and foreach.
I hope I've made myself understood. I'm sure it's a straight forward bit of coding but as a novice I cannot fathom.
thanks in advance for any help
I have searched the internet and googled but I can't locate an answer. I'll keep looking.
thanks
Try following
<?php
foreach ($tag_array as $key => $names ) {
${"arrayitem$key"} = $names;
}
echo $arrayitem0;
?>
You can access variable as $arrayitem0, $arrayitem0 and so on depending upon key ($key) of your $tag_array
I think this is what you are looking for.
<?php
foreach ($tag_array as $key => $names ) {
$."arrayitem".$key = $names;
}
echo $arrayitem6;
?>
you can access variable as $arrayitem0 ,$arrayitem1...till 99
I am using the BandsInTown API, and I'm trying to list all the event titles for a band. The code below works for the first title, but I need to look through all of them. I tried a foreach loop I found on here, but did have any luck. How do I show all the event titles for a particular band? I have been looking at previous questions like this one.
$json = file_get_contents("http://api.bandsintown.com/artists/Skrillex/events.json?api_version=2.0&app_id=MYID");
$data = json_decode($json);
echo $data[0]->title;
// I tried this, but it didn't work
foreach($data->title as $title){
echo $title;
}
I think you might be look for something like
foreach($data as $datum){
echo $datum->title;
}
Try this.,
foreach($data as $Events){
echo $Events->title."<br>";
}
Try..
foreach($data as $item){
echo $item->title;
}
I have a feeling I'm going to get scolded for this but here is the question.
$seq_numbers = range('1', '24');
foreach($seq_numbers as $seq_number)
{
Bullet <?php echo $seq_number;?>
// (this successfully creates - Bullet 1, Bullet 2, etc. -
below is the problem.
<?php echo $db_rs['bullet_($seqnumber)'];?>
} // this one doesn't work.
I've tried
with curly brackets {}
I basically have a few columns that are named same except for number at the end (bullet_1, bullet_2, bullet_3, etc.) and want to get the results using a loop.
Your problem is, that PHP doesn't replace variables inside strings enclosed with single quotes. You need to use $db_rs["bullet_{$seq_number}"] or one of those:
<?php
foreach ($seq_numbers as $seq_number) {
$key = 'bullet_' . $seq_number;
echo $db_rs[$key];
}
Even shorter, but a little less clear:
<?php
foreach ($seq_numbers as $seq_number) {
echo $db_rs['bullet_' . $seq_number];
}
An entirely different approach would be to loop over the result array. Then you don't even need $seq_numbers. Just as an afterthought.
<?php
foreach ($db_rs as $key => $value) {
if (substr($key, 0, 7) == 'bullet_') {
echo $value;
}
}
Oh...and watch out for how you spell your variables. You are using $seq_number and $seqnumber.
<?php echo $db_rs['bullet_'.$seqnumber];?>
why not:
$db_rs['bullet_'.$seqnumber]
If not, what are your fields, and what does a var_dump of $db_rs look like?
try this...
$seq_numbers = range('1', '24');
foreach($seq_numbers as $seq_number)
{
Bullet <?php echo $seq_number;?>
// (this successfully creates - Bullet 1, Bullet 2, etc. -
below is the problem.
<?php echo $db_rs["bullet_($seqnumber)"];?>
} // now it works.
I'm trying to make a universal script that adds keywords to my individual pages (since header is in an include file) so I am getting the end of the url (multi.php) and retrieving the desc etc. from it's array. For some reason instead of returning keywords or descriptions it instead just returns "m" . . . it's kind of random and has me scratching my head. Here's what I got
<html>
<head>
<title>Multi-Demensional Array</title>
<?php
$path = pathinfo($_SERVER['PHP_SELF']);
$allyourbase = $path['basename'];
$pages = array
(
"multi.php" => array
(
"keywords" => "index, home, test, etc",
"desc" => "This is the INDEX page",
"style" => "index.css"
),
"header.php" => array
(
"keywords" => "showcase, movies, vidya, etc",
"desc" => "SHOWCASE page is where we view vidya.",
"style" => "showcase.css"
)
);
?>
</head>
<body>
<?php
foreach($pages as $key => $value)
{
if($key == $allyourbase)
{
echo $key['desc'];
}
}
?>
</body>
</html>
The reason why this is happening is because in PHP if I had the following code:
$hello = 'world';
and I attempted to do the following:
echo $hello[0];
PHP Would treat the string as an array and return me whatever is in position 0, which would result in w, when your using a foreach your asking PHP to set the key of the array to $key, and it's value to $value.
you then echo echo $key['desc'];, as the value is a string, php sees it as an integer based index, so it will ignore your call for desc and then return the first index, if you were to change echo $key['desc'] to echo $value['desc'] which is a hash based array it will return the desired results.
You should just be able to do this:
if(isset($pages[$allyourbase]))
{
echo $pages[$allyourbase]['desc'];
}
No need for the loop
try
echo $key['desc'];
replace with
echo $value['desc'];
Other people have provided some great solutions, but it's important that you understand exactly what is happening here, so you don't make the same mistake again. Pay careful attention to the comments, and you will be on your way to successful coding!
Here's what is happening:
foreach ($pages as $key => $value) {
if ($key == $allyourbase) {
// At this point: $key = 'multi.php'
// Also: $value = array( ... );
// Keep in mind: $key['desc'] = $key[0] = 'm';
// You are grabbing the first letter of the 'multi.php' string.
// When dealing with strings, PHP sees $key['desc'] as $key[0],
// which is another way to grab the very first character of 'multi.php'
echo $key['desc'];
// You really want $pages[$key]['desc'], but below
// is a better way to do it, without the overhead of
// the loop.
}
}
If you kept the loop, which is really unnecessary, it would look like this:
foreach ($pages as $key => $value) {
if ($key == $allyourbase) {
echo $value['desc'];
}
}
The best solution is to replace the loop with the following code:
if (isset($pages[$allyourbase])) {
echo $pages[$allyourbase]['desc'];
} else {
// error handling
}
If I'm reading this right, echo $key['desc']; should be echo $value['desc'];.