I have some code which will feed through the ten most recent Wordpress blog posts through to my own non-Wordpress site. Is there any way to display the featured image assigned to a blog post? I have successfully echoed the blog title, date and body.
<?php
global $text, $maxchar, $end;
function substrwords($text, $maxchar, $end='...') {
if (strlen($text) > $maxchar || $text == '') {
$words = preg_split('/\s/', $text);
$output = '';
$i = 0;
while (1) {
$length = strlen($output)+strlen($words[$i]);
if ($length > $maxchar) {
break;
} else {
$output .= " " . $words[$i];
++$i;
}
}
$output .= $end;
} else {
$output = $text;
}
return $output;
}
$rss = new DOMDocument();
$rss->load('http://myblog.wordpress.com/rss/'); // <-- Change feed to your site
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 10; // <-- Change the number of posts shown
for ($x=0; $x<$limit; $x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$description = substrwords($description, 400);
$date = date('l F d, Y', strtotime($feed[$x]['date']));
echo '<div style="margin-bottom:25px;">';
echo '<h3><strong><a style="color: #139035;" href="'.$link.'" title="'.$title.'" target="_blank">'.$title.'</a></strong></h3>';
echo '<p><small><em>Posted on '.$date.'</em></small></p>';
echo '<p>'.$description.'</p>';
echo '<span> <strong><a target="_blank" style="color: #139035;" href="'.$link.'" title="'.$title.'">Read blog ></span></strong>';
echo '</div>';
}
?>
You can use following code to add featured image into your RSS
function img_in_rss($content) {
global $post;
if ( has_post_thumbnail( $post->ID ) ){
$content = get_the_post_thumbnail( $post->ID, 'medium') . $content;
}
return $content;
}
add_filter('the_excerpt_rss', 'img_in_rss');
add_filter('the_content_feed', 'img_in_rss');
Related
`add_shortcode( 'veg-list', 'veg_list_shortcode' );
function veg_list_shortcode( $atts ) {
ob_start();
echo '';
The taxonomy we want to parse */
$taxonomy = "vegetables_category";
Get all taxonomy terms */
$terms = get_terms($taxonomy, array(
"orderby" => "count",
"hide_empty" => false
)
);
Get terms that have children */
$hierarchy = _get_term_hierarchy($taxonomy);
?>
All Vegetables
parent) { continue;}
echo 'name . '">' . $term->name . '';} ?>
'; /** The taxonomy we want to parse */
$taxonomy = "vegetables_category";
Get all taxonomy terms */
$term = get_terms($taxonomy, array(
"orderby" => "count",
"hide_empty" => false,
"terms_per_page" => 6));
Get terms that have children */
$hierarchy = _get_term_hierarchy($taxonomy);
Loop through every term */
foreach($terms as $term ) {
Skip term if it has children /
//if($term->parent) {
continue;
//}
echo 'name . '">';
If the term has children... /
if($hierarchy[$term->term_id]) {
/ ...display them */
foreach($hierarchy[$term->term_id] as $child) {
Get the term object by its ID */
$child = get_term($child, "vegetables_category");
$category_link = get_category_link($child->term_id);
echo 'name . '"> ' ?>
<div class="caf-featured-img-box" style="background:url(<?php the_field('category_image',$child); ?>)"></div>
<?php endif; ?>
name;?>
'; }}
echo ''; }?>
';?>
`
My Wordpress site use first image as post thumbnail, code:
add_filter('the_content','replace_content');
function get_first_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
if(empty($first_img)) {
$first_img = "/path/to/default.png";
}
return $first_img;
}
Some posts have no image in its content, so i want to use different default thumbnails for them: posts in category A use picture1, posts in cagory B use category2...
How can I do this?
thank you
You need to get the current post category first, then, make a if statement in your code.
Check this link : https://developer.wordpress.org/reference/functions/get_the_category/#comment-305
How about this, here we are using has_post_thumbnail to check for image attachments, if none exist we are setting up the image and image source. From there we check for category assignment, if there are no category matches we use a default thumbnail.
<?php
if ( ! has_post_thumbnail() ) {
$themefolder = get_bloginfo('template_directory');
echo '<img src="' . $themefolder . '/images/';
if ( is_category( 'Category A' ) ) {
echo 'no-image-a.png';
} elseif ( is_category( 'Category B' ) ) {
echo 'no-image-b.png';
} else {
echo 'no-image.png';
}
echo '" alt="' . get_the_title() . '">' . PHP_EOL;
}
?>
Finally, It's my code:
add_filter('the_content','replace_content');
function get_first_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
if(empty($first_img)) {
$categories = get_the_category();
if ( ! empty( $categories ) ) {
foreach ( $categories as $category ) {
if( $category->name == 'Category A' ){ $first_img = "/path/to/default1.png";}
elseif ( $category->name == 'Category B' ){ $first_img = "/path/to/default2.png";}
else {$first_img = "/path/to/default3.png";}
}
}
}
return $first_img;
}
I am retrieving latests post rss from my blog using ?feed=rss2 parameter. I noticed that in the xml structure is missing the featured link image, (the image shown on the blog related to the post).Is there a way to include it?
refer below for detailed functionality,
function rss_post( $atts ) {
//Thirs party website URL
$client_url = "{'url']}";
//gets count of post
$count = "{$atts['count']}";
//return var
$return_val = '';
//replace with your URL
$rss = fetch_feed("$client_url");
if (!is_wp_error($rss)) :
$maxitems = $rss -> get_item_quantity($count);
$rss_items = $rss -> get_items(0, $maxitems);
endif;
//grabs our post thumbnail image
function get_first_image_url($html) {
if (preg_match('/<img.+?src="(.+?)"/', $html, $matches)) {
return $matches[1];
}
}
//shortens description
function shorten($string, $length) {
$suffix = '…';
$short_desc = trim(str_replace(array("\r", "\n", "\t"), ' ', strip_tags($string)));
$desc = trim(substr($short_desc, 0, $length));
$lastchar = substr($desc, -1, 1);
if ($lastchar == '.' || $lastchar == '!' || $lastchar == '?')
$suffix = '';
$desc .= $suffix;
return $desc;
}
//start of displaying our feeds
if ($maxitems == 0) echo '<li>No items.</li>';
else foreach ( $rss_items as $item ) :
$return_val .= '<div class="four columns omega">';
$return_val .= '<div class="pic">';
$return_val .= '<img width="460" height="290" src="'. get_first_image_url($item -> get_content()).' " class="attachment-portfolio-medium size-portfolio-medium wp-post-image" alt="girl_bike-460x290" sizes="(max-width: 460px) 100vw, 460px">';
$return_val .= '</div>';
$return_val .= '<h4>';
$return_val .= ''.esc_html($item -> get_title()).'';
$return_val .= '</h4>';
$return_val .= '<p>'. shorten($item -> get_description(), '150').'</p>';
$return_val .= '<p>Read more</p>';
$return_val .= '</div>';
endforeach;
return $return_val;
}
add_shortcode( 'footag', 'rss_post' );
I'm using this function in my theme's function.php:
function featuredtoRSS($content) {
global $post;
if ( has_post_thumbnail( $post->ID ) ){
$content = '<div>' . get_the_post_thumbnail( $post->ID, 'thumbnail', array( 'style' => 'margin-bottom: 15px;' ) ) . '</div>' . $content;
}
return $content;
}
add_filter('the_excerpt_rss', 'featuredtoRSS');
add_filter('the_content_feed', 'featuredtoRSS');
i am using a custom post type in my site and want to add this post in cart item. i tried this code but not succeeded. this code is rendered as an ajax call from a button.
function buy_now_process_event() {
global $woocommerce;
$items = $woocommerce->cart->get_cart();
if ($_REQUEST) {
$product_id = $_REQUEST['product_id'];
$price_pro = $_REQUEST['price'];
}
if (!empty($items)) {
foreach ($items as $item => $values) {
$_product = $values['data']->post;
echo "<b>" . $_product->post_title . '</b> <br> Quantity: ' . $values['quantity'] . '<br>';
$price = get_post_meta($values['product_id'], '_price', true);
echo " Price: " . $price . "<br>";
}
echo $items['product_id'];
} else {
$woocommerce->cart->add_to_cart($product_id, 1);
}
exit();
}
I've a problem to show a Custom Menu in sidebar.
Now, I've created a Menu from WordPress back-end. this menu must be showed in sidebar of my template, with menu name (i.e. CUSTOM MENU) and the structure with parents and child.
My target is this.
At the moment, I've this part of code:
$meta_box_menu = array(
'id' => 'custom-meta-menu',
'title' => 'Menu Sidebar',
'page' => 'page',
'context' => 'side',
'priority' => 'high',
'fields' => array(
array(
'id' => 'custom-meta-menu-name',
'type' => 'select',
'std' => 'none'
),
),
);
/*
* This function will register the meta box with WordPress
*/
function custom_add_box() {
global $meta_box_menu;
add_meta_box($meta_box_menu['id'], $meta_box_menu['title'], 'custom_meta_menu_html',
$meta_box_menu['page'], $meta_box_menu['context'], $meta_box_menu['priority']);
}
add_action('admin_init', 'custom_add_box');
/*
* This function will produce the html needed to display our meta box in the admin area
*/
function custom_meta_menu_html() {
global $meta_box_menu, $post;
$output = '<p style="padding:10px 0 0 0;">'.__('Scegli il menu da mostrare nella Sidebar di questa pagina.', 'custom').'</p>';
$output .= '<input type="hidden" name="sf_meta_box_nonce" value="'.
wp_create_nonce(basename(__FILE__)). '" />';
$output .= '<table class="form-table">';
foreach ($meta_box_menu['fields'] as $field) {
$meta = get_post_meta($post->ID, $field['id'], true);
/*
* Get out all our menus using the function from functions.php
*/
$menus = custom_get_all_menus();
/*
* Grab out saved data for edit mode
*/
$meta = get_post_meta($post->ID, $field['id'], true);
$output .= '<select name="'.$field['id'].'" class="widefat">';
$output .= '<option value="none">- none -</option>';
if(is_array($menus)):
foreach($menus as $k => $v):
if($meta==$v->slug):
$output .= '<option selected="selected" value="' . $v->slug .'">' . $v->name . '</option>';
else:
$output .= '<option value="' . $v->slug .'">' . $v->name . '</option>';
endif;
endforeach;
endif;
$output .= '</select>';
}
$output .= '</table>';
echo $output;
}
/*
* This function will save our preferences into the database
*/
function custom_save_data($post_id) {
global $meta_box, $meta_box_menu;
foreach ($meta_box_menu['fields'] as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], stripslashes(htmlspecialchars($new)));
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
}
}
add_action('save_post', 'custom_save_data');
function custom_get_all_menus() {
$menu_obj = get_terms( 'nav_menu' );
return $menu_obj;
}
/*
* Html Custom Sidebar Menu
*/
function custom_generate_menu_from_items($items) {
if(count($items)>0):
$menu_list = '<aside class="widget sidebar_menu"><h5 class="widget-title">' .'CUSTOM MENU'. '</h5><nav><ul class="sidebar-menu-items">';
foreach ( (array) $items as $key => $menu_item ) {
$title = $menu_item->title;
$url = $menu_item->url;
$menu_list .= '<li>' . $title . '</li>';
}
$menu_list .= '</ul></nav></aside>';
return $menu_list;
$menu_item->title = get_post_meta( $menu_item->ID, '_menu_item_title', true );
return $menu_item;
endif;
add_filter( 'wp_get_nav_menu_items', 'custom_generate_menu_from_items', null, 3 );
}
With this code, the menu is showed in output page but the pages are placed in the same level, without parent child relationship.
How can I keep this relationship?
Thank you your support.
There is no logic in there that checks the relationships, I'd say
var_dump($items);
somewhere and see if there is some field pertaining to the relationships of the menu items. Probably something looking like "parentId" or along those lines.
If it's not there, then you'll have to query them yourself.
Once you have them, you can check if it has a parentId, and handle the formatting that way. This will get a little tricky if it nest down more than one level, because you'd have to start checking if the parent has a parent and handle the formatting for all those different cases