How to make multiple page IDs simpler (array?) - wordpress

The simple code below:
<?php
$callout_1 = '1';
$callout_2 = '3';
$callout_3 = '5';
?>
<ul>
<li><h3 class="title"><?php echo get_the_title($callout_1); ?></h3></li>
<li><h3 class="title"><?php echo get_the_title($callout_2); ?></h3></li>
<li><h3 class="title"><?php echo get_the_title($callout_3); ?></h3></li>
</ul>
I have lots of more stuff inside the <li> tags, but all has the same structure, the above sample is just an example. Can anyone help me to make it easier please?
Edit: Thanks for the answer Tamil, Can you help me on another question based on this please? If 1 then echo text 1, if 2 then echo text 2 ...

Use array to store the page ids
Try
<?php $callout = array('1', '3', '5'); ?>
<ul>
<?php
foreach($callout as $call) {
?>
<li><h3 class="title"><?php echo get_the_title($call); ?></h3></li>
<?php } ?>

You can create a associative array. Its a multiple array having key=>value pair. Value is accessed by key.
`$callouts = array(array('id'=>1, 'text'=>'text1'), array('id'=>2, 'text'=>'text2'),array('id'=>3, 'text'=>'text3'));`
So now while looping you can print both id and text.
foreach( $callouts as $call ) {
echo '<li><h3>'.get_the_title($call['id']).'</h3></li>';
echo '<p>'.$call['text'].'</p>';
}
If you have to get the value and store in array:
$ids = array('1','2','3');
$callouts = array();
foreach($ids as $id ){
$title = get_the_title($id);
if( $id == 1)
$text = 'Text 1';
elseif($id == 2)
$text = 'Text 2';
else
$text = '';
$callouts[] = array('id'=>$id, 'title'=>$title, 'text'=>$text);
}
To print, you can use single array to print everything.
foreach( $callouts as $call ){
echo '<li><h3>'.$call['id'].'<h3></li>';
echo '<li><h3>'.$call['title'].'<h3></li>';
echo '<li><h3>'.$call['text'].'<h3></li>';
}
Hope this helps

Related

Advanced Custom Fields code displayed as plaintext when written in Code Snippets plugin. How to fix?

On Wordpress, I’m trying to add a link to single product page using Code Snippets with Advanced Custom Fields. Instead of a link, my code displays as plaintext.
I have tried this code:
function product_datasheet_below_summary() { ?>
$link = get_field('datasheet');
if( $link ):
$link_url = $link['url'];
$link_title = $link['title'];
$link_target = $link['target'] ? $link['target'] : '_self';
?>
<a class="button" href="<?php echo esc_url($link_url); ?>" target="<?php echo esc_attr($link_target); ?>"><?php echo esc_html($link_title); ?></a>
<?php
};
add_action( 'ocean_after_single_product_meta', 'product_datasheet_below_summary', 5 );
This doesn’t work. I was hoping for a link to the Datasheet, but it simply prints, in plaintext:
$link = get_field(‘datasheet’); if( $link ): $link_url =
$link[‘url’]; $link_title = $link[‘title’]; $link_target =
$link[‘target’] ? $link[‘target’] : ‘_self’; ?>
followed by a generic square button link.
What am I doing wrong here? Thanks very much for your help.
Thanks for your advice. Instead of using Code Snippets I just created a child theme and edited the relevant .php file, adding the following:
`
if( $link ):
$link_url = $link['url'];
$link_title = $link['title'];
$link_target = $link['target'] ? $link['target'] : '_self';
?>
<a class= "button" id="datasheet-button" href="<?php echo esc_url($link_url); ?>" target="<?php echo esc_attr($link_target); ?>"><?php echo esc_html($link_title); ?></a>
<?php endif; ?>`
You're getting plaintext after the first ?> because that's a php ending tag, and the Code Snippets plugin doesn't allow for multiple php statements and is simply crashing and dumping plain text rather than executing code.
You need to rewrite the whole function as one php statement and echo all the button html, along with the php variables delimited in the html with .'s. A simple example:
<?php
$var = "Hello World";
echo "<p>The value of the variable is : " . $var . "</p>";
?>
And you may need to use the more standard ACF get field construct, too:
$value = get_field( "text_field" );
Search SE for more examples of echoing html in php.
Your function is a bit all over the place, I have cleaned it up to work in the output you want it to using an object instead of echoing out multiple parts of the button code. This in my opinion is easier to manage and looks nicer as it keeps the HTML and PHP code as separate as possible:
function product_datasheet_below_summary() {
$link = get_field('datasheet');
if( $link ){
$link_url = $link['url'];
$link_title = $link['title'];
$link_target = $link['target'] ? $link['target'] : '_self';
} ob_start();?>
<?php if($link):?>
<a class="button" href="<?php echo $link_url;?>" target="<?php echo $link_target;?>"><?php echo $link_title;?></a>
<?php endif;
return ob_get_clean();
} add_action( 'ocean_after_single_product_meta', 'product_datasheet_below_summary', 5 );?>

How to Simply Remove a Specific User_ID from Outputted List

I'm trying to display a "Top 10 Leaderboard" list of users on my Wordpress website who have earned the most points using the popular MyCred plugin. The code I found is working perfectly, however against my wishes, myself as the admin always makes the top of this points list because I am on the website helping people all the time, therefore earning points. But, I don't want to be competitive with other users as admin.
New to PHP, I'm having problems figuring out what I need to add to have it not include me — using my Wordpress user ID (#1) I assume — when it generates the "top 10" list.
Here's the complete code I'm working with that I found on GitHub, but I think the relevant small section of code I need to slightly modify is right here:
// Construct unorganized list for each row
echo '<ul class="mycred-this-weeks-leaderboard">';
foreach ($leaderboard as $position => $data) {
echo '<li>';
$user_info = get_userdata($data->user_id);
$tempname = $user_info->user_login;
$lowerstring = strtolower($tempname);
$stringwithoutspace = strtr($lowerstring, ' ', '-');
$username = preg_replace('/[^a-zA-Z0-9_]/', '-', $stringwithoutspace);
?>
<?php if (!empty($username)) { ?>
<div class="leaderboard-info-block">
<span class="leaderboard-avatar"><?php echo $avatar = get_avatar($data->user_id, 49); ?></span> <span class="leaderboard-profile-link"><?php echo $data->display_name; ?></span> <br>
<span class="leaderboard-user-points"><?php echo $mycred->format_creds($data->total); ?></span>
</div>
<?php
}
echo '</li><br>';
}
echo '</ul>';
Thank you for any help you can give me! :-)
Just skip the code inside loop if the $data->user_id is 1 (your user ID)
if($data->user_id == 1){
continue;
}
To implement that code to yours:
echo '<ul class="mycred-this-weeks-leaderboard">';
foreach ($leaderboard as $position => $data) {
if($data->user_id == 1){
continue;
}
echo '<li>';
$user_info = get_userdata($data->user_id);
$tempname = $user_info->user_login;
$lowerstring = strtolower($tempname);
$stringwithoutspace = strtr($lowerstring, ' ', '-');
$username = preg_replace('/[^a-zA-Z0-9_]/', '-', $stringwithoutspace);
?>
<?php if (!empty($username)) { ?>
<div class="leaderboard-info-block">
<span class="leaderboard-avatar"><?php echo $avatar = get_avatar($data->user_id, 49); ?></span> <span class="leaderboard-profile-link"><?php echo $data->display_name; ?></span> <br>
<span class="leaderboard-user-points"><?php echo $mycred->format_creds($data->total); ?></span>
</div>
<?php
}
echo '</li>';
}
echo '</ul>';

Reversing sort order of ingested RSS feed in PHP

I have a site where I am 'pulling' local events from a secondary website RSS feed. I have this working however the feed is displaying in reverse order with the local events dated later (i.e. at the end of October versus events dated for today) showing up at the top instead of the bottom.
Here is the code I am using for the feed ingest:
<?php if(function_exists('fetch_feed')) {
include_once(ABSPATH . WPINC . '/feed.php'); // include the required file
$feed = fetch_feed('http://sample.com.au/events/feed/'); // specify the source feed
$limit = $feed->get_item_quantity(25); // specify number of items
$semti = array_flip($limit);
$items = $feed->get_items(0, $limit); // create an array of items
}
if ($limit == 0) echo '<div>The feed is unavailable.</div>';
else foreach ($items as $item) : ?>
<p><b><a href="<?php echo esc_url( $item->get_permalink() ); ?>" target="_blank">
<?php echo esc_html( $item->get_title() ); ?></a></b>
<?php echo esc_html( $item->get_date('| j F | g:i a') ); ?><br>
<?php echo sanitize_text_field( $item->get_content() ); ?>
</p>
<?php endforeach; ?>
This works perfectly to get my remote RSS feed and display the title, date of the event and the excerpt, however the order is reverse sorted.
I tried adding filters like "sort and ksort" in the "foreach ($items $items) :" area but this did not work for me. I've racked my brains on this one and am hoping someone can help me out. I appreciate any guidance/help in advance.
Try the appropriately named array_reverse function!
<?php if(function_exists('fetch_feed')) {
include_once(ABSPATH . WPINC . '/feed.php'); // include the required file
$feed = fetch_feed('http://sample.com.au/events/feed/'); // specify the source feed
$limit = $feed->get_item_quantity(25); // specify number of items
$items = $feed->get_items(0, $limit); // create an array of items
$semti = array_reverse($items); // & flip it
}
if ($limit == 0) echo '<div>The feed is unavailable.</div>';
else foreach ($semti as $item) : ?>
<p><b><a href="<?php echo esc_url( $item->get_permalink() ); ?>" target="_blank">
<?php echo esc_html( $item->get_title() ); ?></a></b>
<?php echo esc_html( $item->get_date('| j F | g:i a') ); ?><br>
<?php echo sanitize_text_field( $item->get_content() ); ?>
</p>
<?php endforeach; ?>
From PHP.net:
array_reverse
Return an array with elements in reverse order
array array_reverse ( array $array [, bool $preserve_keys = false ] )
Takes an input array and returns a new array with the order of the elements reversed.

Define the Beginning of a Wordpress Excerpt

I am trying to shave off a few characters or pieces of text we have in our posts. We have the date and source from which the story in our posts cam but I would not like that included in our excerpt and the formatting people insist that it must remain at the top of the post.
How would I go about specifying exactly where I would like the excerpt to begin in the post? Could I have it begin at something like <p> tag or could I set the number of characters to skip before it begins?
Any help would be greatly appreciated. Here is my code thus far:
<phpcode>
<?php $my_query = new WP_Query('category_name=science&showposts=5'); ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<div id="postlist_container">
<h4 class="und"></h4>
<?php get_the_image(array( 'image_scan' => true , 'image_class' => 'small_image_left','width' => 80 , 'height' => 80)); ?><div class="post_desc"><date><?php the_time('M j, Y') ?></date> · <a href="<?php the_permalink() ?>">
<?php the_title(); ?></a> <br /><br /><?php the_excerpt_max_charlength(250); ?>
</div>
</div>
<div class="clear"></div>
<?php endwhile; ?>
<?php
function the_excerpt_max_charlength($charlength) {
$excerpt = get_the_excerpt();
$charlength++;
if ( mb_strlen( $excerpt ) > $charlength ) {
$subex = mb_substr( $excerpt, 0, $charlength - 5 );
$exwords = explode( ' ', $subex );
$excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) );
if ( $excut < 0 ) {
echo mb_substr( $subex, 0, $excut );
} else {
echo $subex;
}
echo '[...]';
} else {
echo $excerpt;
}
}
?>
</phpcode>
If the date/source are always the same length (which is probably unlikely), then you could use substr() on $excerpt to remove X number of characters:
// assume we want to remove the first 10 chars
$chars_to_skip = 10;
// get the full excerpt
$excerpt = get_the_excerpt();
// check the length
if ( strlen( $excerpt ) > $chars_to_skip ){
// remove chars from the beginning of the excerpt
$excerpt = substr( $excerpt, $chars_to_skip );
}
What's more likely is that you would need to do a regex search and replace to remove whatever the pattern matches even when the exact length of the source or date text differs post to post. You could use preg_replace() (api info) to accomplish this, but I can't help with the regular expression not knowing the format you're using.

WordPress - How to do "current-page-item" classes in a list of custom taxonomy terms?

I have the following code that generates a list of terms in a taxonomy term, and then POSTS that are under each term.
I want to have a current-page-item class added to the current item, so that when you are on a page under the taxonomy term, its related item in the nav is styled. Here is my code:
<?php $terms = get_terms('benefit-cats');
echo "<ul>";
foreach ($terms as $term) {
$wpq = array ('taxonomy'=>'benefit-cats','term'=>$term->slug,'order'=>'asc','orderby'=>'title');
$query = new WP_Query ($wpq);
echo "<li class=".$term->slug."><span class=\"list-item\"><span class=\"text-arrow\">►</span> ".$term->name."</span>"; ////
echo "<ul class=\"children\">";
?>
<?php
if ($query->have_posts() ) : while ($query->have_posts() ) : $query->the_post(); ?>
<li><span class="text-arrow">►</span> <?php the_title();?></li>
<?php endwhile; endif; wp_reset_query(); ?>
<?php
echo "</ul></li>";
}
echo "</ul>";
?>
You can try something like this...
Specify the current post_id before your loop, then condition to see if post loop contains your post_id.
// before loop
$page_id = $wp_query->get_queried_object_id();
// replace <li><span class="text-arrow">►</span>
if($page_id ==$query->post->ID ) $class = " current-page-item";
<li><span class="text-arrow<?php echo $class; ?>">►</span>

Resources