Search code examples
wordpressshortcodewordpress-shortcode

How to make a shortcode to list category posts with sorting based on custom field value


I just switched to a new theme and don't want to override the template files. In my old theme I had a custom sidebar.php file with following code above the dynamic widget part. For new theme, I want to do this with a shortcode instead and just use a text widget to place it in the sidebar. How can I convert this to a shortcode?

<aside id="my-listings" class="widget widget-my-listings">
    <h2 class="widget-title">Featured Listings</h2>
    <ul>
        <?php
            global $post;
            $listings = get_posts('category=3&numberposts=-1&orderby=meta_value&meta_key=price&order=DESC');
            foreach($listings as $post) :
        ?>
        <li><a href="<?php the_permalink(); ?>"><?php
        if(get_post_meta($post->ID, "alternate_title", true)) {
            echo get_post_meta($post->ID, "alternate_title", true);
        } else {
            the_title();
        } ?></a></li>
        <?php endforeach; ?>
    </ul>
</aside>

Solution

  • Use this shortcode.

    [mylistingswidget]
    

    This is the code place in your functions.php

    <?php
    
    add_shortcode( 'mylistingswidget', 'my_listings_widget' );
    
    function my_listings_widget( $atts ) {
        ob_start();
        ?>
        <aside id="my-listings" class="widget widget-my-listings">
            <h2 class="widget-title">Featured Listings</h2>
            <ul>
                <?php
                global $post;
                $listings = get_posts('category=3&numberposts=-1&orderby=meta_value&meta_key=price&order=DESC');
                foreach($listings as $post) :
                    ?>
                    <li><a href="<?php the_permalink(); ?>"><?php
                            if(get_post_meta($post->ID, "alternate_title", true)) {
                                echo get_post_meta($post->ID, "alternate_title", true);
                            } else {
                                the_title();
                            } ?></a></li>
                <?php endforeach; ?>
            </ul>
        </aside>
    <?php
        return ob_get_clean();
    }