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.
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:
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.
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:
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:
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:
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.
In this tutorial, we are going to create a simple WordPress plugin that allows you to signin with google to your website. Here is the demo of what we are going to create.
Demo
Table of content
Creating and Activating the Plugin.
Displaying Google One-tap Sign In Popup.
Calling an AJAX in WordPress.
Show Popup to Non-authenticated Users Only.
Replace User Gravatar with Your Image.
Let’s get started
So let’s start allowing your users to signin with google on your WordPress website.
First, go to your wp-content content at the root of your WordPress website. And inside this, go to the plugins folder. Then create a new folder named signin-with-google. This will be our plugin folder, you are free to name it as you like.
Inside this newly created folder, create a new file named signin-with-google.php. This will be our main file. By setting the same name as the folder name, WordPress will automatically pick it up as the main file. Write the following code in this file to view it on the “Plugins” page in the admin panel.
<?php
/**
* Plugin Name: Sign in With Google
* Description: This plugin is for one-tap google sign in.
* Version: 1.0
* Author: adnan-tech.com
**/
Go to your “Plugins” page in your WordPress admin dashboard and you will see your plugin as “Sign in With Google”. You can find the direct link to the plugins folder from the following URL:
https://{your_domain}/wp-admin/plugins.php
You need to “Activate” your plugin in order to make it work.
Displaying google one-tap sign-in popup
To display the Google one-tap Sign-in popup on each page, you first need to generate a Google OAuth client ID. You can generate it from here. Or you can follow our tutorial that will help you set this up.
After the client ID is generated, write the following code in your plugin’s main file:
function SIWG_init()
{
// [user authentication is checked here]
// [JS scripts will be included here]
echo '<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="g_id_onload"
data-client_id="{your_google_client_id}"
data-context="signin"
data-callback="SIWG_googleLoginEndpoint"
data-close_on_tap_outside="false">
</div>';
}
add_action('wp_footer', 'SIWG_init');
Make sure to write your own Google Client ID in place of {your_google_client_id} code. Refresh your frontend side and open your browser console window. You will see an error that you need to create a Javascript function. So we will create a Javascript function that will be called when the user clicks the “Sign in” button on the popup.
So write the following code in the [JS scripts will be included here] section:
Then create the file named SIWG-script.js at the root of your plugin folder. We are appending “?v=1” at the end of the path of the file, it is to prevent the browser from caching this file. If you are making changes in your Javascript code and your changes are not being reflected when you refresh the page, simply increment the “?v=1” counter and it will work fine.
Following will be the code of SIWG-script.js file:
function SIWG_googleLoginEndpoint(googleUser) {
console.log(googleUser);
// [ajax code goes here]
}
Now refresh the page and this time there will be no error. Click the “Sign in” button in the popup and you will see the credential object in the browser console. On the client-side, Google only returns this credential also known as ID Token. We will send this ID Token to the server to verify the user.
Calling an AJAX in WordPress
To send an AJAX in WordPress, we need to include a built-in WordPress library called wp-util. So write the following code in the [include WP util] section:
// Manually enqueue the wp-util library.
wp_enqueue_script( 'wp-util' );
After that, we need to call an AJAX from Javascript. So replace the [ajax code goes here] section with the following code:
Now we need to create an API in our plugin’s main PHP file that will handle this request.
// a function that will handle the AJAX request
function SIWG_google_login()
{
// secure credential value from AJAX
$credential = sanitize_text_field($_POST["credential"]);
// verify the ID token
$curl = curl_init( 'https://oauth2.googleapis.com/tokeninfo?id_token=' . $credential );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
$response = curl_exec( $curl );
curl_close( $curl );
// convert the response from JSON string to object
$response = json_decode($response);
// if there is any error, send the error back to client
if (isset($response->error))
{
wp_send_json_error($response->error_description);
}
else
{
// check if user already exists in WordPress users
$user_id = username_exists( $response->email );
if ( ! $user_id && !email_exists( $response->email ) )
{
// user does not exists
// generate a random hashed password
$random_password = wp_generate_password( $length = 12, $include_standard_special_chars = false );
// insert the user as WordPress user
$user_id = wp_insert_user([
"user_email" => $response->email,
"user_pass" => $random_password,
"user_login" => $response->email,
"display_name" => $response->name,
"nickname" => $response->name,
"first_name" => $response->given_name,
"last_name" => $response->family_name
]);
}
// do login
$user = get_user_by('login', $response->email );
if ( !is_wp_error( $user ) )
{
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID );
wp_set_auth_cookie ( $user->ID );
// set user profile picture
update_user_meta($user->ID, "SIWG_profile_picture", $response->picture);
}
// send the success response back
wp_send_json_success( $response );
}
}
add_action( 'wp_ajax_nopriv_SIWG-google-login', 'SIWG_google_login' );
Comments have been added with each line for an explanation. Refresh the page now and when the popup is displayed, click on the “Sign in” button. Your browser page will refresh automatically after a few seconds. And you will see that the user is now logged-in.
You can also see the user in the admin panel dashboard.
Show popup to non-authenticated users only
Users who are already logged in to your site should not be seeing the popup as they are already logged in. So we need to show this popup only for users who are not logged in. So write the following code in the [user authentication is checked here] section:
if (is_user_logged_in())
{
return false;
}
It will simply stop the function from executing if the user is already logged in.
Replace user gravatar with your image
We are saving the user profile picture URL from google in our user metadata using the key “SIWG_profile_picture“. Now we need to display it. To do that, we need to add a filter that will update the WordPress Gravatar image with the URL saved in the database. Add the following code in your plugin’s main PHP file.
function SIWG_override_avatar( $avatar, $id_or_email, $size, $default, $alt )
{
//If is email, try and find user ID
if( ! is_numeric( $id_or_email ) && is_email( $id_or_email ) )
{
$user = get_user_by( 'email', $id_or_email );
if( $user )
{
$id_or_email = $user->ID;
}
}
//if not user ID, return
if( ! is_numeric( $id_or_email ) )
{
return $avatar;
}
//Find URL of saved avatar in user meta
$saved = get_user_meta( $id_or_email, 'SIWG_profile_picture', true );
//check if it is a URL
if( filter_var( $saved, FILTER_VALIDATE_URL ) )
{
//return saved image
return '<img src="' . esc_url( $saved ) . '" alt="' . esc_attr( $alt ) . '" />';
}
//return normal
return $avatar;
}
add_filter( 'get_avatar', 'SIWG_override_avatar', 10, 5 );
By adding the above code, if the user is logged-in and is registered by Google, then his profile picture will be displayed as in his google account. Otherwise, it will be displayed by WordPress gravatar.
So that’s how you can enable your site’s visitors to signin with google on your wordpress website. This will definitely increase the number of daily registrations. Because it is a quicker way for the users to join.
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:
From your WordPress admin panel, go to “Plugins > Plugin Editor”.
Select plugin to edit “Share a Draft”.
Select plugin file “shareadraft.php”.
Search for 2 variables; “$my_unpublished” and “$others_unpublished”.
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
) );
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 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:
Setting
Value
Carousel Image size
Original uploaded image
Auto Width
Disabled
Columns
1
Columns: Desktop
1
Columns: Small desktop
1
Columns: Tablet
1
Columns: Small tablet
1
Columns: Mobile
1
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:
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 / Linux
ctrl + shift + delete
Mac
command (⌘) + 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.
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.
Install and activate the plugin named “Stripe Payments by wptipsntricks”.
Then you will see “Stripe Payments” menu on left sidebar on admin panel. Goto Stripe Payments > Settings.
Scroll down and you will see 4 fields:
Live Stripe Publishable Key
Live Stripe Secret Key
Test Stripe Publishable Key
Test Stripe Secret Key
Goto your stripe dashboard and from left sidebar, goto Developers > API keys.
Copy the publishable and secret key and paste them in respective fields. Make sure if you are using test mode or live mode.
Coming back to your WordPress admin panel, goto Stripe Payments > Add New Product.
In “Price & Currency” section, select “Donation”.
You will also see a section named “Embed Product” on right hand side below “Publish” button.
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 Number
5555 5555 5555 4444
Expiry Month
02
Expiry Year
22
CVC
314
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.