Sort custom post type by ID ascending – WordPress

Suppose you have custom post type in WordPress that you want to sort such that it displays the first created post on top. By default, WordPress sort the posts by ID in descending. That means that the latest uploaded post will be displayed on top, which is good in many cases. But there might be a scenario where you want the first post to be displayed first. In this post, we will teach you how to do it using our Social Network API custom post type.

First, you need to go to your WordPress admin panel and navigate to Appearance -> Theme File Editor. In that page, select your current theme and find it’s “index.php” file and open it. In this file, search for a code:

<?php if ( have_posts() ) : ?>

Inside this “if” condition, and before the while loop:

<?php while ( have_posts() ) : the_post(); ?>

Write the following code, make sure to replace “social-network-api” with your own custom post type where you want to apply this sort.

<?php if ( have_posts() ) : ?>
                        
    <?php
        $post_type = $_GET["post_type"] ?? "";
        if ($post_type == "social-network-api"):
            query_posts([
                "post_type" => $post_type,
                "posts_per_page" => 10,
                "orderby" => "ID",
                "order" => "ASC"
            ]);
        endif;
    ?>

    <?php while ( have_posts() ) : the_post(); ?>

    <?php endwhile; ?>

<?php endif; ?>

If you refresh the page now, you will see your first post be displayed first.

WordPress – Disable multiple image sizes

If you are using WordPress, you will notice that when you upload an image media, it creates multiple images of different resolutions. In this article, I will show you how you can disable multiple image sizes on WordPress.

Open your active theme’s functions.php file. It will be in “wp-content/themes/{your_active_theme_name}/functions.php”. Then add the following 2 hooks at the top of functions.php file:

function wpb_remove_image_sizes($sizes) {
    unset($sizes['thumbnail']);
    unset($sizes['medium']);
    unset($sizes['medium_large']);
    unset($sizes['large']);
    return $sizes;
}
add_filter('intermediate_image_sizes_advanced', 'wpb_remove_image_sizes');

function wpb_stop_generate_media_sizes($sizes) {
    return array();
}
add_filter('intermediate_image_sizes', 'wpb_stop_generate_media_sizes');

Refresh the page and try uploading a new image. You will now see that it will be uploaded just once. Let me know if you face any problem in this.

Decode HTML entities in WordPress PHP

In this article, we are going to tell you, how you can decode HTML entities in your WordPress post using PHP. For example, if you write &copy; in your blog post, it will be displayed as ©.

To do that, you need to create a simple WordPress plugin. Go to your “wp-content” folder, then to the “plugins” folder. Inside this folder, create a new folder named “decode-html-entities”. Inside this newly created folder, create a file named “index.php”. Inside this file, you only need to write the following code:

<?php

/**
 * Plugin Name: Decode HTML entities
 */

function decode_html_entities_from_content($content)
{
	return html_entity_decode($content);
}

function decode_html_entities()
{
	// to filter post by ID
	$post = get_post();
	if ($post->ID == 9)
	{
		add_filter("the_content", "decode_html_entities_from_content");
	}

	// to filter posts by category
	$categories = get_the_category();
	if (!empty($categories))
	{
		foreach ($categories as $category)
		{
			if (strtolower(esc_html($category->name)) == "php")
			{
				add_filter("the_content", "decode_html_entities_from_content");
			}
		}
	}
}

// this action hook executes just before WordPress determines which template page to load
add_action("template_redirect", "decode_html_entities");

After that, you need to go to your admin dashboard and activate the plugin. You will see the plugin named “Decode HTML entities” on your “plugins” page. If you want to know more about the “template_redirect” hook, you can learn it from its official documentation.

That’s how you can decode HTML entities from your WordPress posts in PHP. Check out our more free tutorials on WordPress.

[wpdm_package id=’1882′]

Show WordPress posts in PHP website

In this tutorial, we will teach you how to show WordPress posts in your PHP website. Make sure you run this code from inside your server where the WordPress blog is hosted. This means that if your WordPress blog is hosted on the main domain like “adnan-tech.com”, then this code should be on any of the sub-domain like “web.adnan-tech.com”.

And vice versa, if your WordPress blog is hosted on a sub-domain like “blog.adnan-tech.com”, then this code should be on the main domain like “adnan-tech.com”. This script will not work on localhost because many of the WordPress blogs have some security plugins installed, that prevent any external host to fetch data from it.

Show WordPress posts in PHP

To show all the blog posts from your WordPress website, we will be using WordPress posts API. Just write the following code in the file where you want to show the blog listing. Make sure to change your blog URL in $blog_api_url variable:

<?php
    $blog_api_url = "https://yourblogdomain/wp-json/wp/v2";

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $blog_api_url . "/posts",
        CURLOPT_RETURNTRANSFER => 1
    ]);
    $response = curl_exec($curl);
    curl_close($curl);
    
    $posts = json_decode($response);
    foreach ($posts as $post)
    {
        $id = $post->id;
        $date = date("d M, Y", strtotime($post->date));
        $slug = $post->slug;
        $status = $post->status; // "publish"
        if ($status != "publish")
        {
            continue;
        }
        $link = $post->link;
        $title = $post->title->rendered;
        $excerpt = $post->excerpt->rendered;
    
        $curlMedia = curl_init();
        curl_setopt_array($curlMedia, [
            CURLOPT_URL => $blog_api_url . "/media/" . $post->featured_media,
            CURLOPT_RETURNTRANSFER => 1
        ]);
        $responseMedia = curl_exec($curlMedia);
    
        $responseMedia = json_decode($responseMedia);
        $mediaTitle = $responseMedia->title->rendered;
        $altText = $responseMedia->alt_text;
        $mediaSourceUrl = $responseMedia->source_url;

        ?>

        <div style="border: 1px solid black; margin: 10px; padding: 10px;">
            <?php if (!empty($mediaSourceUrl)) { ?>
                <img src="<?php echo $mediaSourceUrl; ?>" alt="<?php echo $altText; ?>" title="<?php echo $mediaTitle; ?>" style="width: 100%;" />
            <?php } ?>
            
            <div>
                <p><?php echo $date; ?></p>
                <h2>
                    <a href="./show-post.php?slug=<?php echo $slug; ?>">
                        <?php echo $title; ?>
                    </a>
                </h2>
                <p><?php echo $excerpt; ?></p>
            </div>
        </div>

    <?php
    }
?>

This will fetch the latest posts from your WordPress blog. We are looping through all the posts and saving the necessary variables from the $post object. You can write print_r($post) inside the foreach loop to view an entire $post object. We are only displaying the published posts here. If you want to show the unpublished posts as well, simply comment out the continue; statement. Inside the foreach loop, we are calling another CURL request to get the featured image of the post.

Blog listing

Then, we are creating a <div> inside the foreach loop with a 1-pixel black border and a 10 pixels margin from all sides. We are also giving it a 10 pixels padding so it will margin from inside too. Inside this div, we display the post’s published date, title, and excerpt. An excerpt is a short text from the blog post, you can set it up from the WordPress admin panel for each post separately. If not specified, then it will be the first paragraph of the post.

We are making the title a hyperlink, so when clicked, it will redirect the user to a new page where we can show that post in detail. We are using “./” in the hyperlink because our post detail page is in the same directory. You can also redirect the user to the original post on the WordPress blog using the variable $link. We didn’t put the hyperlink on the image, because if the post does not have a featured image, then the link will not be created. And the user will have no option to redirect to the post detail page.

Single post

To show the post detail inside your website, simply create a file named show-post.php and write the following code in it:

<?php
    $slug = $_GET["slug"];
    $blog_api_url = "https://yourblogdomain/wp-json/wp/v2";

    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $blog_api_url . "/posts?slug=" . $slug,
        CURLOPT_RETURNTRANSFER => 1
    ]);
    $response = curl_exec($curl);
    curl_close($curl);

    $posts = json_decode($response);
    if (count($posts) == 0)
    {
        die("Post not found.");
    }
    
    $date = date("d M, Y H:i:s", strtotime($posts[0]->date));
    $status = $posts[0]->status; // "publish"
    if ($status != "publish")
    {
        die("Post not published.");
    }
    $title = $posts[0]->title->rendered;
    $content = $posts[0]->content->rendered;

    $curlMedia = curl_init();
    curl_setopt_array($curlMedia, [
        CURLOPT_URL => $blog_api_url . "/media/" . $posts[0]->featured_media,
        CURLOPT_RETURNTRANSFER => 1
    ]);
    $responseMedia = curl_exec($curlMedia);

    $responseMedia = json_decode($responseMedia);
    $mediaTitle = $responseMedia->title->rendered;
    $altText = $responseMedia->alt_text;
    $mediaSourceUrl = $responseMedia->source_url;
?>

<!-- Post title -->
<h1><?php echo $title; ?></h1>

<!-- Post meta content -->
<p>Posted on <?php echo $date; ?></p>

<!-- Preview featured image -->
<?php if (!empty($mediaSourceUrl)) { ?>
    <img src="<?php echo $mediaSourceUrl; ?>" alt="<?php echo $altText; ?>" title="<?php echo $mediaTitle; ?>" style="width: 100%;" />
<?php } ?>

<!-- Post content-->
<section>
    <?php echo $content; ?>
</section>

This will show the post title in the heading. Date the post was published. Featured image if available, the featured image will also have an alt text that will be displayed in case the image is not found. It will also have a title attribute that will be visible when the user moves the mouse over the image (hover effect). Finally, we are displaying the complete content of the post.

Show comments of the post

To show the comments of the post, first, we need to fetch all the comments of the post. We are again going to use the CURL request on WordPress comments API. Write the following code below post content:

<?php
    $curlComments = curl_init();
    curl_setopt_array($curlComments, [
        CURLOPT_URL => $blog_api_url . "/comments/?post=" . $posts[0]->id,
        CURLOPT_RETURNTRANSFER => 1
    ]);
    $responseComments = curl_exec($curlComments);
    $responseComments = json_decode($responseComments);

    foreach ($responseComments as $comment) {
        if ($comment->status != "approved") {
            continue;
        }
?>
    <div style="border: 1px solid black; margin: 10px; padding: 10px;">
        <?php foreach (((array) $comment->author_avatar_urls) as $avatar_url) { ?>
            <img src="<?php echo $avatar_url; ?>" style="width: 100px;" />
        <?php break; } ?>

        <p><?php echo $comment->author_name; ?></p>
        <p><?php echo $comment->content->rendered; ?></p>
    </div>
<?php } ?>

This will first fetch all the comments of that post. Then it will loop through each comment and will skip the loop iteration if the comment is not approved yet. Then, it will create a <div> tag with styles the same as we did for the blog listing. The author_avatar_urls object in each $comment is an object. So we need to convert that to an array using (array) typecasting. Then we will loop through it, and display the profile image of the user who posted that comment. After that, we are using a break statement so it will not show multiple images, it will stop the loop after displaying one image. User profile images are in different dimensions, but we need to show only one. And finally, we display the name of the person who posted the comment and the comment itself.

Check out our more tutorials on WordPress.

Source code – Show WordPress posts in PHP

[wpdm_package id=’1747′]

Or you can also download it from Github.

Share a Draft, Getting Only 5 Posts [FIXED] – WordPress

In this tutorial, we are going to teach you, how you can display all posts in your Share a Draft plugin in WordPress. This plugin is used to share your unpublished posts using a link. In WordPress, by default only published posts are shared. You can download the plugin manually from here.

Video tutorial:

You just need to follow the steps below:

  1. From your WordPress admin panel, go to “Plugins > Plugin Editor”.
  2. Select plugin to edit “Share a Draft”.
  3. Select plugin file “shareadraft.php”.
  4. Search for 2 variables; “$my_unpublished” and “$others_unpublished”.
  5. Add the “nopaging” value in the “get_posts” function of both of these arrays.
$my_unpublished = get_posts( array(
	'post_status' => $unpublished_statuses,
	'author' => $current_user->ID,
	// some environments, like WordPress.com hook on those filters
	// for an extra caching layer
	'suppress_filters' => false,
	"nopaging" => true
) );
$others_unpublished = get_posts( array(
	'post_status' => $unpublished_statuses,
	'author' => -$current_user->ID,
	'suppress_filters' => false,
	'perm' => 'editable',
	"nopaging" => true
) );
  1. Click the “Update File” button and refresh your plugin page.

Then you will be able to view all of your drafted posts.

Learn how to fix your WP Carousel Slider plugin height issue following this tutorial.

WP Carousel slider plugin height issue [Fixed]

WP Carousel Slider is a WordPress plugin developed by Sayful Islam. This plugin allows you to create carousel images in your blog post. You can display your media images, gallery, custom URLs, blog posts, or WooCommerce products in the carousel.

It works as sliders, so you need to create a new slider, and add images to that slider. A shortcode will be generated for each slider, you just need to place that shortcode in your post where you want to show the slider. Sliders created from this plugin can also be used as widgets.

In this article, I am going to discuss a solution to a problem that occurs when you try to add images with different heights in your slider under the following configurations:

SettingValue
Carousel Image sizeOriginal uploaded image
Auto WidthDisabled
Columns1
Columns: Desktop1
Columns: Small desktop1
Columns: Tablet1
Columns: Small tablet1
Columns: Mobile1

If you are using the above settings and if you upload the images with different heights in a slider, then you might see that slider has been given a height of the largest image which will create a lot of empty space at the bottom of the smaller height images.

Moreover, when you scroll between carousel items, the height of the carousel is not auto-adjusted. Let me explain how you can solve this.

Solution:

You need to make 1 change in the plugin file. When it comes to editing the plugin files, there are 2 options.

1. WordPress admin panel

From your WordPress admin panel, go to “Plugins > Plugin Editor” and select the “Carousel Slider” plugin. When this plugin is selected, go to the following path:

assets/js/frontend.js

2. File manager

If you prefer to use file manager instead of making the changes from the WordPress admin panel, then you need to go to the following path:

wp-content/plugins/carousel-slider/assets/js/frontend.js

Replace the content of the “frontend.js” file with the following:

Before applying the solution, please prepare a backup of this file. Copy the content of this file and paste it into your computer’s Notepad.

If you have prepared the backup of this file, feel free to replace the file’s code with the following:

function setOwlStageHeight(event) {
    var maxHeight = 0;
    jQuery('.owl-item.active').each(function () { // LOOP THROUGH ACTIVE ITEMS
        var thisHeight = parseInt( jQuery(this).height() );
        maxHeight=(maxHeight>=thisHeight?maxHeight:thisHeight);
    });
    jQuery('.owl-carousel').css('height', maxHeight );
    jQuery('.owl-stage-outer').css('height', maxHeight ); // CORRECT DRAG-AREA SO BUTTONS ARE CLICKABLE
}

jQuery("body")
    .find(".carousel-slider")
    .each(function () {
        let a = jQuery(this),
            e = a.data("auto-width"),
            t = parseInt(a.data("stage-padding"));
        if (
            ((t = t > 0 ? t : 0),
            jQuery().owlCarousel &&
                (a.owlCarousel({
                    stagePadding: t,
                    nav: a.data("nav"),
                    dots: a.data("dots"),
                    margin: a.data("margin"),
                    loop: a.data("loop"),
                    autoplay: a.data("autoplay"),
                    autoplayTimeout: a.data("autoplay-timeout"),
                    autoplaySpeed: a.data("autoplay-speed"),
                    autoplayHoverPause: a.data("autoplay-hover-pause"),
                    slideBy: a.data("slide-by"),
                    lazyLoad: a.data("lazy-load"),
                    autoWidth: e,
                    navText: [
                        '<svg class="carousel-slider-nav-icon" viewBox="0 0 20 20"><path d="M14 5l-5 5 5 5-1 2-7-7 7-7z"></path></use></svg>',
                        '<svg class="carousel-slider-nav-icon" viewBox="0 0 20 20"><path d="M6 15l5-5-5-5 1-2 7 7-7 7z"></path></svg>',
                    ],
                    responsive: {
                        320: { items: a.data("colums-mobile") },
                        600: { items: a.data("colums-small-tablet") },
                        768: { items: a.data("colums-tablet") },
                        993: { items: a.data("colums-small-desktop") },
                        1200: { items: a.data("colums-desktop") },
                        1921: { items: a.data("colums") },
                    },
                    autoHeight: true,
                    onInitialized: setOwlStageHeight,
                    onResized: setOwlStageHeight,
                    onTranslated: setOwlStageHeight
                }),
                "hero-banner-slider" === a.data("slide-type")))
        ) {
            let e = a.data("animation");
            e.length &&
                (a.on("change.owl.carousel", function () {
                    a.find(".carousel-slider-hero__cell__content")
                        .removeClass("animated " + e)
                        .hide();
                }),
                a.on("changed.owl.carousel", function (t) {
                    setTimeout(function () {
                        jQuery(t.target)
                            .find(".carousel-slider-hero__cell__content")
                            .eq(t.item.index)
                            .show()
                            .addClass("animated " + e);
                    }, a.data("autoplay-speed"));
                }));
        }
        jQuery().magnificPopup &&
            ("product-carousel" === a.data("slide-type")
                ? jQuery(this).find(".magnific-popup").magnificPopup({ type: "ajax" })
                : "video-carousel" === a.data("slide-type")
                ? jQuery(this).find(".magnific-popup").magnificPopup({ type: "iframe" })
                : jQuery(this)
                      .find(".magnific-popup")
                      .magnificPopup({ type: "image", gallery: { enabled: !0 }, zoom: { enabled: !0, duration: 300, easing: "ease-in-out" } }));
    });

After replacing the above code, you need to refresh your browser cache in order to see the effect. Press the following keys to remove the browser cache:

Windows / Linuxctrl + shift + delete
Maccommand (⌘) + shift + delete

When you hit the above keys, you will see a pop-up asking which data you want to delete. You will have 3 options and you need to check the “Cached files and images” option. Also, make sure to select “All time” from the “Time range” option.

Now refresh the post where you have placed the shortcode for the WP Carousel Slider plugin, and you will know that the carousel will adjust itself dynamically with the height of the currently active image.

How to get donations from Stripe in WordPress

In this tutorial, we are going to teach you how you can get donations in your WordPress site for non-profit organizations using Stripe. We assume that you already have registered a Stripe account and a WordPress site.

We will be using a WordPress plugin to get donations.

Learn how to integrate Stripe using Javascript.

Stripe Payment Gateway – Javascript, PHP

Following are the steps:

Video tutorial:

  1. Goto Plugins > Add New.
  2. Search for “Stripe”.
  3. Install and activate the plugin named “Stripe Payments by wptipsntricks”.
  4. Then you will see “Stripe Payments” menu on left sidebar on admin panel. Goto Stripe Payments > Settings.
  5. Scroll down and you will see 4 fields:
    • Live Stripe Publishable Key
    • Live Stripe Secret Key
    • Test Stripe Publishable Key
    • Test Stripe Secret Key
  6. Goto your stripe dashboard and from left sidebar, goto Developers > API keys.
  7. Copy the publishable and secret key and paste them in respective fields. Make sure if you are using test mode or live mode.
  8. Coming back to your WordPress admin panel, goto Stripe Payments > Add New Product.
  9. In “Price & Currency” section, select “Donation”.
  10. You will also see a section named “Embed Product” on right hand side below “Publish” button.
  11. Copy the shortcode and paste that in your post or wherever you want to show the payment button.

Now, you can use the following credentials for testing the payment method:

Card Number5555 5555 5555 4444
Expiry Month02
Expiry Year22
CVC314

Whenever someone makes a donation to your site, you will see that in your Stripe dashboard “Payments” page from the left sidebar. You can follow this link for sandbox accounts. For live accounts, simply remove the “test” part from the URL.

Note: I will add Stripe payment gateway for getting donations in your website in just $5.