How to Load More Posts using Ajax with a Button or on Scroll in WordPress

Updated: 22/09/2021 – Further clarification has been added on the setup of this script.

In today’s post, we will show you how to create a load more button to show additional posts or custom post types using AJAX.

The benefit of this is that it will improve the page-load of the particular page as it will only be displaying a certain amount of posts before having to load any more of the content (especially when you are loading images).

So let’s get started…

So the first thing that you should have is a list of posts to display on the frontend as follows:-


    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

Then you want to add the following code in your functions.php file where you register the scripts:


	wp_localize_script( 'core-js', 'ajax_posts', array(
	    'ajaxurl' => admin_url( 'admin-ajax.php' ),
	    'noposts' => __('No older posts found', 'twentyfifteen'),
	));	

To further explain this, in my example I enqueue scripts as follows:


wp_register_script( 'core-js', get_template_directory_uri() . '/assets/js/core.js');
wp_enqueue_script( 'core-js' );

wp_localize_script( 'core-js', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Firstly, you would enqueue the file where you will be adding the JS code to, then you will add the wp_localize_script code after you have enqueued the core.js file. This has to be done like this otherwise you will get an error such as Can’t find variable: ajax_posts.


NOTE: You will need to replace code-js with the file you are going to be adding the JS code later in this tutorial.

We added it to a file called core.js, and the reason we added code-js is that we enqueued the script as follows:


	wp_register_script( 'core-js', get_template_directory_uri() . '/assets/js/core.js');
	wp_enqueue_script( 'core-js' );

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file, you need to add the function that will load your posts:-


function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

The final part is the ajax itself. In core.js or your main JavaScript/jQuery file, you need to input inside the $(document).ready(); environment the following code:-


var ppp = 3; // Post per page
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                //$("#more_posts").attr("disabled",false); // Uncomment this if you want to disable the button once all posts are loaded
                $("#more_posts").hide(); // This will hide the button once all posts have been loaded
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
    $(this).insertAfter('#ajax-posts'); // Move the 'Load More' button to the end of the the newly added posts.
});

With the above code, you should now have a load more button at the bottom of your posts, and once you click this it will display further posts. This can also be used with CTP (custom post type).

How to add Infinite Load, instead of Click

You can also load the rest of the posts automatically on scroll instead of having to click on a button. This can be achieved by making it invisible by setting the visibility to hidden.

The following code will run the load_posts() function when you’re 100px from the bottom of the page. So instead of the click function we added we would use:


$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Do note that there is a drawback to this. With this method, you could never scroll the value of $(document).height() - 100 or $('footer').offset().top, If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.log in your code and see in the inspector what they throw out like so:


$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();        
    }
});

Adjust the settings accordingly and you will get this working to your desire in no time!

If you need any help with this, feel free to get in touch in the comment below. If you need help with this, just drop me a message and I’ll be more than happy to help you!

 


Sponsor

If you have come this far and you’re a fan of Football, check out our sponsor below; The FPL Way. We have just created an excellent tool for them; The FPL Planner.

They will help you become the king of your FPL mini-leagues!


Fantasy Premier League – Gain the FPL advantage you deserve

 

Silva Web Designs - Profile

Posted by: Silva Web Designs

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

7 Tips to Stand Out as a Freelance Web Developer

Today, I will share you with my top 7 top tips for finding your feet in becoming a full-time Freelance Web Developer. I have been working as a Freelance Developer now for just over eight years and it has been my full-time job now for over five years.

It most certainly isn’t the easiest job to get started but it’s very rewarding once you can sustain regular work and achieve your monthly income targets. Standing out as a freelancer, especially as a web developer can be quite tough as it’s quite a competitive world out there. However, due to the increase of technology, web developers are more in demand these days. If you’re going to start, I would definitely recommend freelancing in your spare time to build up some clients and tackle a lot of the tasks I am going to talk about below. For instance, I started freelancing whilst I was working a full-time job for other companies. The main reason I did this was to put me in a better position to survive more comfortably as opposed to simply diving straight into the deep end and constantly searching for work.

If you are a web developer, I would recommend working for a few digital agencies so that you can acquire all the tech-related skills you need. By doing this, you will then also gain the features and skills of web developments that can help you serve more easily as a freelancer.

Once you become a freelancer, you will be able to work on your own terms and you will be the boss; trust me, it’s a great feeling. If you are ready, then here are my top 7 tips to help you get started.

Tips to Become a Successful Freelancer Web Developer

To stand out from the crowd as a freelancer, here are some tips and strategies you should consider to become more successful:

1. Learn Required Skills & Identify Your Niche

To start, you will need to further develop your web development skills such as HTML, PHP, JavaScript, jQuery, CSS, and many others. It would also be very beneficial to understand and learn more about a variety of CMS platforms such as WordPress, Magento, Shopify, and so on. By further developing your skills and focusing on them, you will attain the specific requirements of some clients so that you can deliver that job. Being a freelance developer, people must acknowledge you as the best one to go to. It will enhance your portfolio as you can mention your specific areas of expertise.

2. Needs to be Pro-active

To be an effective freelancer, you need to be more active and focused. Asides from waiting for projects and recommendations, you have to take a big step up and take the lead role. Have a look for some potential clients and approach them with your offers and services. A lot of freelancers avoid looking for clients and prefer waiting for references and this avoidance can be the biggest mistaking in your freelancing career. You’re the boss now, you need to put your energy into your everyday life to track potential clients and approach them in a professional manner. Since a lot of freelancers fail to do this, it is a great way to get ahead of your competition and stand out on the top list for your potential clients.

There are several freelancing websites available today which is exactly how I got started. The main ones I used initially were:

 

There are a few other ones you could use as well such as Freelancer and Fiverr, although I did find more success on the three I mentioned above.

Start by building a profile that stands out from the crowd, provide all the services you offer and start submitting your proposals for jobs; even if it’s just a simple small task. On these freelancing platforms, you get feedback once you deliver a job, the more feedback you receive, the more likely a potential client is going to pick you for the next job.

You will be surprised with the clients you can meet on these websites, they can quite often lead to giving you regular jobs moving forward. Not only that, but I have even worked with a few digital agencies that can supply you with regular work. This can be even better for you as they have a team of designers who can supply you with design mockups and then it becomes your job to only build the website. I myself have landed jobs as a contractor which came about from a freelancing website. This means I have a contract to work a set amount of hours per month which gives me a guaranteed wage at the end of the month. These can be hard to come by but trust me, they will come over time and it makes life a lot easier as you won’t have to constantly apply for jobs; more work, more money right?

3. Build an Attractive Website / Portfolio

This is a very important aspect that can help you in your freelancing life. If you create an attractive, eye-catching website displaying your skills and portfolio, it will for sure pique your client’s attention. It’s a great tool to demonstrate all the services and skills you offer as well as a reference point so potential clients can look at what sort of jobs you have delivered in the past. For example, I created a portfolio page so people can check out the websites I have built. It is the best marketing device to take the lead in your field.

4. Use Social Media Platforms

Everyone scrolls endlessly on social media platforms in their daily lives so it’s always advantageous to make use of this to benefit your freelancing career. Update all of your social profiles with the skills, services, and projects you have worked on to attract more clients through these platforms. LinkedIn is one of the most effective social media platforms for approaching clients as recruiters give more priority to this platform to hire freelancers and full-time employees.

Other than that, set up a Twitter, Facebook, and YouTube channel; it will only benefit you by being on more platforms. For example, on your YouTube channel, you could showcase your skills and tips to make yourself a brand. Furthermore, you can offer your services at affordable prices, which will help you approach new clients.

5. Generate Connections

If you want to be successful in becoming a full-time freelancer, you will need to build professional connections to promote yourself. Use relevant networking websites like LinkedIn and learn the ways of generating connections for better reach. In this highly competitive field, it can be a difficult task to attain freelancing projects in the beginning so building connections can certainly help you along the way. Try sharing some of your articles, commenting on appealing posts and engaging more with them to help get your name out there.

6. Holding Up Powerful Clients

Once you find powerful clients, try not to let them go so easily. Remember, they can provide you with regular work which will make you far more productive, i.e. less time looking for work and more time devoted to getting jobs done and getting paid. The most effective way to hold your clients is to deliver your best services and meet your deadlines. Be honest with your client, if a job is going to take two weeks, be sure to tell them that so you can firstly stick to your deadline and deliver on time. Furthermore, be sure to respond to them professionally and notify your clients of your progress. If for some reason you feel that you won’t be able to meet a deadline, let them know in advance and ask for an extension, the earlier you do this, the better. Another tip is to invoice your work properly which can reduce conflicts during payments. For example, you can agree on upfront payment of 50% and then request the final 50% once the job is completed. You can even create milestones if you prefer and agree on getting paid for each milestone you deliver. Trust me, fewer conflicts will build more trustworthy relations.

7. Ask For Feedback From Your Clients

After offering your services to your satisfied clients, ask for their feedback and recommendations. Approach them to recommend your works and services to their friends and colleagues to help promote yourself and gain jobs in the future. If you go above and beyond the client’s expectations on a job, you will most certainly be rewarded and they might spread the word anyway. You could even approach this by offering discounts to these clients if they preferably recommend you and bring in more clients. Moreover, these positive feedbacks and testimonials will certainly help you to expand and generate more income.

Conclusion

Starting as a freelancer in the web development sector is not as easy as it sounds. However, you can make yourself the best service provider by pushing in more effort through proactivity. Asides from offering the best services and having more skills, always update yourself with the latest technologies so you can stand out from the crowd.

Did you find this article useful? Let me know in the comments below. Even if you are thinking of embarking on the journey, my inbox is always open to help people wanting to take on this career path.

 

Silva Web Designs - Profile

Posted by: Silva Web Designs

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

6 Easy Steps to Rank New WordPress Content Faster

Want to rank new WordPress content quickly?

Sometimes it takes some time for search engines to index new content, so your site may not appear in current searches or receive a lot of traffic.

However, it would be best if you never ignored the ranking of your new content.

Many site owners don’t know this, but if you, as a WordPress website owner, don’t place much importance on the ranking of your content, you won’t be able to drive traffic to your website. It would be best to consider the ranking of your content from day one.

When you do this, your site can get a lot of research and fantastic traffic. Same as pre-orders integrated through the WooCommerce pre-order plugin create much of the hype for launching the product. In addition, the ranking of your content will continue to improve as your WordPress site gains more authority in search engines.

However, various websites initially have difficulty getting organic traffic. WordPress SEO practices should be implemented or deployed to address this.
Following are the six easy ways to rank your new content for WordPress faster.

1. Install an SEO plugin

Any WordPress site needs an SEO plugin to change the way its pages are displayed on search engines. And when it comes to SEO plugins, AIOSEO and Yoast SEO are probably some of the most popular choices.

To do this, you need to install and enable the All in One or Yoast SEO plugin for WordPress.

All in One SEO makes it easy for WordPress to do SEO without any special skills. Yoast SEO has many built-in features that allow you to manage your website’s SEO directly.

The plugin displays an installation command that walks you to the beginning upon activation. Configuring the SEO plugin automatically does most of the SEO work. For example, if an SEO tag or description is missing, a plugin may be created automatically for you.

But with these plugins premium versions, you can do more to increase the ranking of your new content search.

2. Add Google Search Console

It is a free tool that helps website owners track the performance of their website in search results.

This will allow you to track your results and receive notifications when Google cannot crawl or index any pages on your site. You can also use the website to notify Google of any updates automatically.

3. Configure XML site map

The WordPress Sitemap is a list of all the public URLs on the WordPress website. Sitemaps help visitors and search engines navigate quickly and easily across all URLs on a single site. They can also show the distance between different pages and the value of each page.

WordPress maps also tell search engines about pages on your site that they haven’t indexed before. It shows the structure and organisation of web pages by providing a complete list of standard URLs.

This will help meet your website’s needs by notifying your website’s search engines that there are no duplicates. Sitemaps also make your site more user-friendly, which improves its position on search engine results pages (SERPs).

4. Perform Content Optimisation

It is the process of ensuring that content is well written to reach a wide range of audiences. Web content research is essential for writing all content, but it’s also crucial that landing pages include information about other aspects of the content.

This should include indexing search terms, adding metrics and tags, and related links. You should also add headlines to increase your CTR and visibility to increase your customer experience.

As with images, be sure to optimise the description and title tags when you post a video to your site, as search engines use these tags to understand the content and context of the video.

Once your video is good, many websites you can use to host your videos, such as YouTube and Vimeo, offer inline code that you can put into HTML your website, allowing visitors to watch your videos directly on your page, but not. You should visit the video site. Edit the video file name as you would for the images, that is, by adding keywords.

5. Internal linking

Communication is necessary before your business can be organised. Google is more likely to find your posts and pages if you link to something online. Internal links lead to your content and give Google an idea of the structure of your site.

They can queue your site, allowing you to rank the most important pages and promote more relevant links than other less important pages. Therefore, using internal links can improve your SEO.

An internal linking means strategically distributing your site’s links on your content. Links worked for both your users and search engines to find the content of your website.

Your users use the links to navigate your website and search for content that interests them. Links are essential for your visitors as well as search engines. 

6. Integrating Social Signals

Social signals are related to the collective sharing, liking and general visibility of a website on social media, as perceived by search engines. This representation contributes to the ranking of organic search on a page and is viewed as another citation form similar to backlinks.

Social media is now more than just messaging and finding ways: it affects your content for SEO. This is why it is more important than ever for the content marketer to create a creative marketing strategy that promotes the best content to deliver value to your visitors. 

Wrapping up

Think of a way to ensure your new item is listed and sorted correctly. The easiest way to track this is to use Google Analytics. Google Analytics is used to track website performance and visitors.

It can help organisations identify key sources of human traffic, measure the success of their marketing and advertising activities, track goals (sales models, add products to the drive), explore patterns and trends in human interactions, and find your visitors information such as demographics.

 

Silva Web Designs - Profile

Posted by: Silva Web Designs

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

6 Reasons Why WordPress is Ideal in Startup Companies Today

Online presence is critical for any business looking to become a profitable venture. This is especially the case for startups that must leverage modern techniques. They can use a website to sell their ideas to stakeholders and their target audiences.

If you’ve just launched your startup, you’re probably worried about building a website. If you’ve already passed that phase and are thinking about the best platform, how about WordPress? A free website creation platform that’s ideal for startups. It allows startups to edit and alter the appearance of their websites without using code.

Every business needs a website, especially if it’s new and needs to grow into a successful venture. If you have no idea where to start, it’s important to seek help from a digital marketing agency for startups.

Getting a professional with a speciality in your business takes a lot off your shoulders. It gives you time to take care of other matters concerning your startup.

Usually, startups are short on cash, making it difficult to get experts to work with. Hiring a professional website developer enables a business to have its digital marketing strategy in order. So, how much should a startup spend on marketing?

According to experts, a startup should spend 12%-20% of the gross revenue on marketing.
Depending on the business strategies, you can figure out how to budget for the money. This is why it’s important to have an effective startup marketing agency.

A business needs to have a powerful digital presence to grow. Presently, customers Google businesses while comparing them to competitors. If you have a weak website or are not on the internet, you lose the game to your competitors. So marketers are leveraging digital marketing tactics, which has enabled them to increase their conversion rates.

The Benefits of WordPress for Startups

Many businesses, established and startups don’t know how beneficial WordPress is. Neither do they know why they need to use it for their businesses. In this article, we give you reasons why it’s a platform worth considering.

Let’s get started!

1. WordPress is Free

Nothing sounds better to a cash-strapped entrepreneur than hearing that WordPress is free. Which begs the question, so what’s the catch? WordPress is open source. Meaning that it’s not owned by anyone.

This website creation platform is backed by a billion-dollar company, Automattic. It also has the backing of volunteers all over the world who’re constantly working to improve it.

The platform is licensed under the General Public License. This makes it free for those who want to build websites. Users have access to free themes, updates, and plugins from the WordPress repository.

Just to make one thing clear. Yes, WordPress software is free. But that doesn’t mean that you will run a website at zero costs. There are costs attached to hosting, the domain name, and customisation.

Startup’s Scalability

As exciting as it can be, starting a business is challenging. So, how do you ensure that you are on the right path? You must integrate professionals and technology to make your business grow. By technology, in this case, we are talking about WordPress.

Apart from WordPress, you also need to seek the services of a startup branding agency. A properly funded startup branding strategy forms a roadmap for the company. It leads the company towards growth in the industry.

Advertising is another important tool for a successful startup. Now, advertising for startups is not as easy considering the limited resources. But that’s not to say that it’s impossible. Especially if you’ve adopted the use of WordPress, a free platform that can be used to talk about your products and services.

When using WordPress, you can display your ads in the sidebar. By using WordPress widgets, you can add Google Adsense in your sidebar. Then choose whether you want your ad to be fixed or responsive. This enables any visitor to your site to get to know more about what you do. In the long term, you start to reap the benefits

WordPress is Secure

When it comes to the security of a website, no platform is 100% safe. Especially when hackers are always devising ways of accessing company websites. WordPress hasn’t been spared either, considering its growing popularity.

What makes it a better platform is that it’s fairly safe. Reason being that it’s constantly monitored for security threats. Aside from that, its users are always quick to raise any security concerns. The platform is also prompt in releasing security updates. It also takes care of minor updates automatically by default.

As a user, it’s important to note that the security of your website is your responsibility. Select a reliable host with quality themes and plugins. Ensure that you have strong usernames and passwords. Also, be sure to update WordPress regularly. You should also backup your website every once in a while to enhance its security.

Extensive Plugins

Websites have different needs depending on different company operations. While some may be selling products, others may want an interactive community. WordPress provides a platform for different kinds of websites. It also allows companies to add functions that will enable them to achieve their goals.

WordPress gives you the liberty to choose a plugin from the more than 50,000 plugins in their repository.

The free plugins are great additions to a startup’s website. They can also add on functions whenever the need arises in business. For instance, a company may not need a live chat on its website at the beginning. But as time goes and the need arises, they can easily add a plugin for the needed functions.

WordPress is Mobile-Friendly and Easy to Use

There are more people today accessing the internet via mobile devices. And just so you know, Google doesn’t take kindly to websites that aren’t compatible with smartphones.

That is not something to worry about though, as WordPress has everyone covered. The technology it uses is compatible and can create web pages for smartphones. It also has a series of free and premium themes, with the ability to adapt to the size of the user’s screen.

When it comes to ease of use, WordPress has one of the best features. You can use it even without knowing any code. It’s just like working with any other processor. A startup can create web pages from a user-friendly interface. Not to pour cold water on the importance of basic coding skills, but even without them, you can still enjoy using WordPress.

The platform has courses, training, videos, podcasts, and blogs to assist you. It excels at Do-it-yourself, and even newbies can create content. It also allows you to embed third-party content like Vimeo and YouTube.

It’s Flexible and Customised

The other best thing about WordPress is its flexibility. The platform comes loaded with Javascript libraries that constitute jQuery.

Every theme on WordPress has in-built customisation characteristics that are easy to customise. The premium themes have built-in drop and drag features which are also easy to customise.

WordPress is so simple to use, it’s like finding one of the best webinar platforms, once you have found a great solution, you simply carry on using it.

Final Thoughts

If you’re an entrepreneur who’s just launched a startup, this article must have been informative. Now you’re well informed about WordPress and why your business needs it. As an entrepreneur, you certainly know the importance of saving on money and time, which WordPress offers.

The market has different types of content management systems, but they’re expensive. Consider choosing WordPress to help you get your business to the world.

 

Silva Web Designs - Profile

Posted by: Silva Web Designs

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

Top 5 WordPress Plugins to Improve On-Site Search

The website pages do not load as fast as they should be — this is the most common problem for web designers. Such a flaw may cause sales to decline. It’s really concerning to marketers as buyers become less patient. This is especially true for people who use mobile devices. If consumers do not see the page loaded after a maximum of 2-3 seconds, they click “back” in the browser or close the window.

Of course, most incidents affect the effectiveness of sales. To fix such flaws, the developers suggest installing a variety of plugins that improve the attractiveness of the web resource, including on-site search tools. In addition, your site’s position in Google results also depends to some extent on loading speed. So, such a problem has to be solved somehow. We will talk about this in our article.

Best Products & Tips for Use

On sites with a lot of pages, the searching bar is becoming more important. Marketers are confident that any slowdown in loading speeds will negatively affect the customer experience and reduce the purchase likelihood. While navigation is useful, it is the search bar that will provide the user with the most viewed content. So, no developer can do without plugins and other tools. Created for different programming languages, such add-ons may differ in essence and characteristics. Here are the most popular products for those who prefer WordPress:

#1. Ajax Search

This is the best plugin that helps shoppers find products in an online store. Most consumers want to see results in 2-3 seconds. With Ajax Search, they certainly won’t be disappointed. It’s a highly customisable product — people can display thumbnails, icons, prices, and promotions with real-time results. This bar can also be added to various categories or store pages. Besides, the Ajax plugin runs on multilingual platforms.

With Ajax Search, people can find products or SKUs. This tool displays prices, images, and descriptions along with an “Add to Cart” button that pops up right into the form. Although this sometimes has the opposite effect and makes it harder to work with the platform. To keep it simple, website caching can be configured to save all pages to disk as static files for faster display. Such a method is best for hosting based on fast SSD drives.

#2. SearchWP

In these golden days, when the market is saturated with goods, and the competition is getting tougher every year, a variety of tools and techniques are very useful for online sales. SearchWP is the most common custom bar for stores based on WordPress. Installing such an add-on is definitely the right step. This tool allows all site visitors and moderators to search for a keyword in the post/page title, different content. Besides, people can customise it in categories, articles or visual content, tags, and even comments. This significantly speeds up page loading. The same goes for snippets or taxonomies.

Of course, the installation of the SearchWP is a good solution for most websites. This is confirmed by dozens of reviews from developers and aspiring entrepreneurs. Such a tool offers the best features and it is affordable for any business. SearchWP is compatible with WooCommerce that makes the promotion of all products extremely effective. Although to use the add-on correctly, people will have to tinker a little with the settings.

Developers offer to control the algorithm by using numbers from 1 to 10 (with 10 being the highest) for all types of content. Such customisation makes it easier to filter pages and monitor the activity. SearchWP is very effective for forums, crypto exchanges like ICOholder, and other platforms. Upon activation, this plugin will automatically index all content that was previously published on the web resource and replace the default engine that integrates into all WordPress web resources.

#3. ElasticPress

It’s another popular search service for WordPress that is based on ElasticSearch. Such a tool performs cloud searches through third-party platforms and shows results at lightning speed. Installing ElasticPress is the best way to increase visitor engagement. Such a plugin provides detailed information about search behaviour. This means that the store owners — by analysing the activity — will be able to draw conclusions about the effectiveness of SEO. The ElasticPress is easy to use and can be integrated into any WordPress website. Among the main advantages of the product:

  • Faster, more accurate search
  • Friendly interface
  • Flexible customisation
  • Versatility

This system instantly shows results when users start typing. So if you have hundreds of pages on your online store, this plugin will come in handy. Such functionality works well on any WooCommerce platform.

#4. Ivory Bar

The Ivory is a common WordPress plugin available for free. Providing excellent capabilities for both the managers and buyers, a universal tool helps to increase sales. This bar is installed by over 10,000 users. With such a platform, people can create new custom forms as well as integrate the bar into any part of the code.

If you want to buy it, there are two options to choose from: Pro Plan starts at $19.99 annually or as a lifetime license for $99.99. With an easy-to-use search builder, people can customise content to suit specific requirements. This tool offers pages grouping and autocompletes as well as instant results, JavaScript, or API integration.

#5. WP Google Bar

If you are looking for a free solution with the highest performance, this is the best version. By installing WP Google, people can replace the default functionality with a custom tool. Setting all parameters is simplified as much as possible:

  • The first step is to create a Google Custom Bar for your website.
  • After that, developers must copy the engine ID and paste it into the bar settings.

This tool ranks all results by relevance, not date. This means all visitors will see content that is in line with marketing trends. Most sites run this bar without any problems since the functionality is very flexible.

In Summary

Since search tools are the backbone of any web resource, it makes sense to install a plugin that delivers advanced functionality on your site. It is the best way for marketers to track analytics and consumer behaviour. Any search bar is key for sales funnel or usability. Take a look at sites like eBay or Amazon to make sure that the problems that we have covered in this article are relevant.

 

Silva Web Designs - Profile

Posted by: Silva Web Designs

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

Useful WordPress Plugins For Writers & Authors

Many people still think that authors need a muse and inspiration. But with modern authors, things are a little different. Now, in addition to inspiration, they also need many tools to create outstanding and competitive articles.

WordPress is one of the most effective and useful platforms for creating various websites. If we talk about writing and blogging, then often such specialists choose this particular functionality. The availability of a variety of plugins allows authors to get all the tools they need in one place to create the best copy for both the audience and search engines. Let’s review the most effective ones.

Top 12 Must Have Plugins for For Writers & Authors

Want to make your writing process simple and efficient? Do it easily with the following best plugins for writers and authors.

1. Just Writing

If jokes about procrastination don’t sound funny to you and that’s your problem, then this plugin can be your lifesaver. It can be very difficult to create quality content when you get distracted every minute. The plugin will make it easier to write text using various functions that may be required while writing. For example, you can instantly check grammar, cut, copy, and so on. The maximum convenience and usefulness of the features will allow you to stop postponing the writing process until later.

2. WP Inject/ImageInject

Writers almost always have to deal with images to support their text with visualisation. Text without images does not engage readers as much as it used to. Authors are aware that it can take a long time to find the appropriate image, download the desired format, save the link, and after adding the image to the site. WP Inject facilitated this task. Also, the plugin will allow you to properly split the text so that your publication and images look harmonious in the final result.

3. Co-Author Plus

Does your site involve collaboration with other authors? Perhaps you have a news resource or platform with user reviews. Anyway, this plugin is the best collaboration tool. It allows you to provide access for publication by another author. In this case, you can select either one author or several (guest mode), and this applies to pages as well. For example, co-authors do not need to have a special profile to make a publication.

4. NextScripts

Writing compelling texts is only half of the job. The second half is to make sure your target audience actually accesses and reads it. This plugin allows you to help your copy get more reach through social media. That is, this tool can automatically duplicate your content on social networks. Therefore, this plugin is a must-have for anyone who wants to get more traffic and readers.

5. Akismet

Receiving a lot of comments and questions is one of the goals most authors pursue when creating their content. And that’s great! But when you have a lot of comments, you also need to manage them properly by filtering and removing spam. This plugin will do all the work you need to do with unwanted comments.

That is, this tool will delete comments that look like spam. After you try this plugin at work, there is no doubt that you will forget about what spam comments are.

6. JetPack

This plugin is a multifunctional tool that is suitable not only for writers but also for everyone who deals with the site and content. The advantage of this tool is that it is a kind of constructor. You can choose only those functions that are right for you. You can set up automatic publication of your texts on different platforms. There are also various functions that will facilitate the process of working on the text.

7. Yoast SEO

Perhaps, this is one of the plugins that can be considered a must-have for all site owners. The authors are certainly no exception. The plugin is available for free with a good arsenal of functions, as well as in the paid version, which has a few more features. It will allow you to improve your text from an SEO point of view so that you can promote your content as effectively as possible.

8. OptInMonster

To win a loyal audience, it is important to constantly convert your prospective leads into loyal readers. The easiest and most effective way to do it is to create lead capture forms. This plugin will just help you create newsletter forms and the best CTA so that your readers stay with you. What’s more, with it you can test several options and find the one that works for your leads best.

9. Nimble Portfolio

Every author should be able to properly demonstrate their work, and this plugin is a real solution for this purpose. Now you can design your services and promote them like top writing websites. The advantage of the plugin is that it allows you to create an excellent portfolio, the quality of which will not change with the desktop or mobile version.

10. Visual Editor Font Size

The desire to enlarge the font during the creation of the text is perhaps a common desire among all writers who work with WP. It’s no secret that the WP offers a default font size, and this is a common problem for many users. This plugin is easy to use, with which you can choose the font size you want without editing the code. That is, the plugin will not affect the actual font size of your site.

11. Copyright Proof

Copyright protection is a hot topic at all times. In the era of digitalisation, every author should think about how to protect their work as well. With this plugin, you can secure your text, and, if necessary, you can prove your copyright. Therefore, if you want your texts not to be duplicated somewhere else by third-party authors, then be sure to download this plugin.

12. WProofreader

Most authors always use additional tools to ensure the quality of their text. With this plugin, you can forget about a lot of third-party tools, as it will instantly fix mistakes as you enter your text. Ready to boost your articles to a professional scale like the top-notch authors featured by the college essay writing service reviews platform create? This WP plugin can help.

If you work with topics that require the use of terminology, then you can customise the dictionary. This plugin can replace such tools as Hemingway Editor or Grammarly. Check out Grammarly Review for more information.

P.S. They are also worth considering solutions in addition to all the plugins we have listed above.

Conclusion

Stop waiting for inspiration, download the plugins you need, and start creating great texts. The effectiveness of these plugins will be your inspiration for creating awesome content again and again.

 

Silva Web Designs - Profile

Posted by: Silva Web Designs

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

3 Effective Tips for Creating a Compelling Online Course Using WordPress

Want to spread your knowledge by creating a compelling online course using WordPress? WordPress can help you significantly in generating more online learners for your online course. Learning online has been integrated to a large extent in people’s lives. Learning is a never-ending process, and people will continue to want to better their talents and learn new things. Why not make money from your knowledge if you have it?

Whatever your talent, now is the moment to seize this opportunity, share your talents with others, and be compensated for your work. Learn how in this article.

Why Should You Create a Compelling Online Course?

According to Statista, the market for online courses has exploded in recent years, with the global online learning market valued at 101 billion dollars in 2019. Especially after the emergence of the Covid-19 pandemic, people have turned more toward learning online. This adds up to the necessity of creating a compelling online course using WordPress.

How to Create a Compelling Online Course Using WordPress?

To start your journey as an online educational entrepreneur, you’ll need a solid Learning Management System (LMS) platform. Luckily, you may not need to be concerned because WordPress makes creating an online course to share your knowledge and experience with the rest of the world simple.

Let’s quickly get to know the 3 effective tips for creating a compelling online course using WordPress.

Decide on Your Course and Plan for it

Regardless of the speciality, all successful entrepreneurs will begin by planning their strategy ahead of time. Well, it is not just about creating online courses that you should go on based on a plan. Rather, every adult performance requires planning to turn out successful. Some people try to keep their distance from planning because they may find the planning phase scary. However, it is an important step that you should never underestimate.

Here are some of the phases you should think about during the planning stage:

1. Choose Your Niche

You surely know what you are an expert at. But when it comes to online learning, you should teach a specific field. If you are an expert in digital marketing, your online course should be specifically about email marketing, or SEO content marketing, social media marketing, etc. If you are an expert in website development, you should specify your online course to teach HTML, or CSS, JavaScript, etc.

So, forget about teaching a bulk of general material that does not add any value to your online learners. Be specific and teach them something useful and practical.

To do this, you need to ask yourself some questions:

  • What is my expertise?
  • Am I capable of explaining the fundamentals of that profession to a novice till they comprehend it?
  • How enthusiastic am I about that particular topic of study?
  • Can you teach a variety of topics in the same field, or will it be a one-time session?

Moreover, you should also analyze the market. Check if there is enough demand for what you want to present. You can do so by searching through the online course websites.

2. Target Your Audience

Choosing a group of audience for your online course is another phase of planning. Having analysed the market, you should then select the type of audience you want to target with your learning resources. To do so, you need to ask yourself another set of questions:

  • How knowledgeable should they be?
  • What kind of tone should I use?
  • To what extent should my explanations be technical or straightforward?
3. Create a Lesson Plan

If you’ve decided to teach the course to a wider audience, you should divide it into numerous modules or lessons, each of which is more technical than the one before it. Start with a simple introduction to the course and then add up to its professionalism.

In addition, try to think of fun examples and interactive short breaks during the course so that your course would not get boring.

4. Prepare for Your Course

The last step of planning for your online course is to think of the methods you want to adopt. What methods will you employ to help your students grasp the subject more clearly? You can use a variety of methods, including slide shows, pictures, graphs, pdfs, movies (explainer videos), screen recordings, and so on.

Consider the templates and samples you’ll need, and don’t forget to make the resources you’ll be using available for your online learners. Also, remember to provide transcripts especially if your target audience does not speak the same mother tongue as you.

Allow users to participate in feedback sessions for more practice and training. Determine whether you need to create a group in one of the messaging apps or social media platforms where students may engage, share knowledge, and work together. You can think of a platform within your WordPress website as well.

It is totally up to you whether to decide on taking an assessment test at the end of your online course. If you think that would consolidate the material.

5. Assess Your Course

Developing an online course is a never-ending process that necessitates extensive testing and revisions. After you’ve completed your initial setup, share the course with a few people to gather feedback. Check to see if the course is covering every issue, if any parts are difficult to understand, and what the appropriate price for the course should be. The very last step is to remember to use all-in-one accounting software to manage your income.

Create Your WordPress Website

After you’ve finalized your course outline and finished detailed planning, the next step is to choose a domain name, select a hosting package, and then create your WordPress website.

As we mentioned earlier, you’ll need to choose a Learning Management Systems (LMS) plugin while you develop your WordPress site.

Some online teaching platforms work nicely with WordPress. One plugin that works great with WordPress and is indeed made by WordPress is LearnPress. This LMS plugin is one of the top WordPress LMS Plugins for effortlessly creating and selling online courses. You can construct a course curriculum with lessons and quizzes that are managed through a user-friendly interface. With this WordPress LMS Plugin, you can develop education, online school, and online-course websites fast and easily, with no coding skills required.

Here are some of LearnPress features:

  • It works with any WordPress theme.
  • LearnPress supports multi-sites.
  • LearnPress LMS plugin has a great user interface for building online courses with all the features you need. It is simple to create a complete curriculum layout, as well as to edit and maintain it.
  • You can share, manage, and check your course’s statistics
  • LearnPress is free.
  • You can sell your courses with many payment methods.
  • Through the WordPress forum, you can communicate with your online learners…
  • There are a lot of add-ons.

Cross-Promote Your Online Course

So here is the situation now: you have planned your online course efficiently, you have created a WordPress website with an LMS plugin, and now you are waiting for the online learners. How can you let others know about your online course? How can you address your target audience? Well, in the era of technology, that is not a big deal. However, it requires you to be persistent in making efforts.

To attract more visitors to your website, you should:

  • Create a blog and optimise it with SEO techniques and SEO content marketing.
  • Do some backlink building to scale your WordPress website traffic.
  • Create a YouTube channel and use it to share some of your knowledge (you already know that YouTube pays its channel owners if they have a lot of engagement, don’t you?)

  • Develop an affiliate program by hosting webinars on one of the topics covered in the course.
  • Consider publishing your work on Quora and Medium.
  • Pay for advertising that is targeted to your audience (Google Ads, Facebook ads, Youtube ads, Instagram ads, Twitter ads, etc.)
  • Make contact with industry influencers who can help you promote your business.
  • Use other social media such as Instagram and Facebook or Club House.

Conclusion

Sharing your knowledge is an admirable thing that you want to do and it shows your generosity. We understand that you may have financial motivations but you have chosen to teach and earn money among a thousand other ways you could have chosen. So, congratulations! Follow the tips above to put your thoughts into practise and teach as many people as you can. Wish you the best of luck!

Speaking of planning, have you checked out the FPL Planner from The FPL Way? It’s a project we have worked on for quite a lot of time which demonstrates how planning can be made easier with online tools.

Parichehr Parsi - Profile

Posted by: Parichehr Parsi

I am Parichehr Parsi, co-founder of SEO Builders, a freelance content creator, and a link builder. I love reading, writing, and doing research.

 

It’s good to share

How to Install and Setup WordPress Multisite Network

In this article, we are going to explain how you can easily install and set up WordPress multisite. So if you are running multiple WordPress sites on sub-domains and wanted to manage all their sites together, we will show you how to install and set up WordPress multisite network.

What is WordPress Multisite?

A WordPress multisite network allows you to run and manage multiple WordPress sites from a single WordPress installation. You can create new sites instantly and manage them using the same username and password. You can even allow other users to signup and create their own blogs on your domain.

Advantages of using a Multisite Network

  1. As the network admin, you can easily administer multiple sites from a single dashboard.
  2. Each site can have its own admins with capabilities to manage only their own site.
  3. Install plugins and themes on multiple sites with one download.
  4. Multisite network also makes it easier for you to manage updates. You only need to update your WordPress, plugins, or themes on one install.
  5. Disadvantages of using a Multisite Network

    1. All the sites on the network share the same resources, so when your site is down, all sites on your network are down.
    2. Managing server resources in case of unexpected traffic can be difficult for a beginner level user.
    3. If your site gets hacked, then this means all the sites on your network will get hacked.
    4. Some WordPress plugins may not work well on a multisite network.

    Who Needs a WordPress Multisite Network

    Just because you have multiple WordPress installation does not mean that you need to create a multi-site network. You can use services like ManageWP or InfiniteWP to manage multiple different sites.

    Creating a multisite network makes sense for:

    • A magazine site with different sections managed by different teams.
    • A business site with sub-sites for different locations and branches.
    • Government or non-profit sites can use multisite for different departments, locations, and regions.
    • Your own network of blogs running on multiple subdomains.
    • Schools and colleges allowing students to create their own blogs on school servers.

    Requirements for a WordPress Multisite Network

    The most important thing you will need to run a WordPress multisite network is good WordPress hosting. If you are not planning to create many sites and do not expect many visitors, then you can get away with shared hosting. However, due to the nature of multi-sites, you’d probably need a VPS or dedicated server as your sites grow.

    Apart from web hosting, you will need some basic knowledge of installing WordPress and editing files using FTP.

    Choosing a Domain Structure for Your Multisite Network

    On a WordPress multisite network, you can have your sites installed as either subdomains or subdirectories, for example:-

    http://sitename.example.com
    http://example.com/sitename/

    If you choose subdomains, then you will have to configure wildcard subdomains on your server.

    On the other hand, if you choose sub-directories or path based URLs for sub-sites on your network, then the only thing you need to do is enable pretty permalinks on your root site.

    Enabling WordPress Multisite Network Feature

    Multisite Network feature comes built-in with each WordPress install. All you need to do is install and set up WordPress like you normally would.

    You can also enable the Multisite feature on an existing WordPress site. Before you enable multisite, make sure that you have created a full backup of your WordPress site.

    To enable Multisite, you need to access your site using an FTP client or cPanel file manager and open wp-config.php file for editing.

    You need to add this line to your wp-config.php file just before the /* That’s all, stop editing! Happy blogging. */ line.

    
    define( 'WP_ALLOW_MULTISITE', true );
    

    Save and upload your wp-config.php file back to the server. Now your WordPress site supports a multisite network.

    Setting up The Network

    Now that you have successfully enabled the Multisite Network feature on your WordPress site, it is time to set up your network. Before you do that, the first thing you need to do is deactivate all plugins on your site. After that, you need to go to Tools > Network Setup to configure your multisite network.

    On the network setup screen, you will see a notice that you need Apache’s mod_rewrite module installed on your server to set up a multisite network. This module is installed and enabled on most reputable WordPress hosting providers.

    The next thing you need to do is to tell WordPress what kind of domain structure you will be using for sites in your network, e.g. Subdomains or Sub-directories. After that, you would need to provide a title for your Network and make sure that the email address in the Network Admin Email is correct. Lastly, click on the install button to continue.

    On the next screen, WordPress will show you some rules that you need to add to your wp-config.php and .htaccess file. Use an FTP client to edit those two files and copy-paste the code.

    Configuring Network Settings

    After successfully setting up the Multisite Network, you need to switch to the Network Dashboard to configure network settings, add new sites, and do lots of other things. Take your mouse over to My Sites menu in the admin toolbar, a fly down popup will appear. Click on Network Admin > Dashboard.

    You will notice that there are new menu items to manage your multisite network. You will also see a dashboard widget allowing you to create a new site and add new users.

    To configure Network Settings click on the Settings link in the admin sidebar. On the network settings screen, the first option is to set your site title and admin email address. These fields will be filled with the network title and admin email you entered during the network setup.

    Opening Your Multisite Network for Registrations

    The Registration Settings section on the network settings screen is probably the most important setting in your network setup. By default, both user and site registrations will be disabled on the network. You can choose to open your site for user registration, or allow existing users to create new sites, or allow both user and site registration.

    You can check the box next to Registration Notification to receive email notifications every time a new user or site is registered.

    If you want to allow the site administrators the ability to add new users to their sites, then you can check the box next to Add New Users.

    Limited Email Registration options will allow you to limit site or user registration to the email address from specific domains, then you can add those domains here. This is particularly useful if you only want to allow people from your own organisation to register and create users or sites. Similarly, you can also ban certain domains from registration.

    New Site Settings

    The New Site Settings section on the network settings screen allows you to configure default options for the new sites created on your network. You can modify the welcome emails and the contents of the first default post, page, and comment.

    Upload Settings for Your Multisite Network

    It is important for you to keep an eye on the usage of the server resources. Under the Upload Settings section, you can limit the total amount of space a site can use for uploads. The default value is 100 MB which is probably good for at least 100 photo uploads. You can increase or decrease this space depending on how much disk space you have.

    The default upload file types are images, audio/video, and pdfs. You can add additional file types if you want, e.g. doc docx odt. Lastly, you can choose a file size limit, so that users can’t upload insanely large files to the server.

    Menu Settings

    Under the menu settings, you will find the option to enable the administrative menu for the plugins section on the network sites. Enabling this will show the plugins menu to site admins. They can activate or deactivate a plugin on their individual sites, but they cannot install new plugins.

    Adding New Sites to Your WordPress Multisite Network

    To add a new site to your WordPress multisite, simply click on Sites under My Sites » Network Admin » Sites menu in the admin toolbar.

    This will show you a list of sites on your current Multisite installation. By default, you have your primary site listed as the only site in your WordPress Multisite network. To add a new site, click on the Add New button at the top.

    On the Add New Site screen, you need to provide the site’s address. You don’t need to type the full address, just the part you want to use as a subdomain or sub-directory. After that provide a site title, and add the site’s admin email address.

    You can add an admin email address other than the one you are currently using to manage your multisite. If the email address is not currently in use by another user on your site, then WordPress will create a new user and send the password and username to the email address you enter.

    Once you are done, click on the Add Site button. A new site will be added to your multisite network. As the network admin, you will receive a new site registration email. If you created a new user, then that user will receive their username and password with instructions to log in on the email address you provided.

    Adding Themes and Plugins to Your Multisite Network

    By default, individual site administrators cannot install themes and plugins on their own. As the network admin, you can install plugins and themes for them and make those themes/plugins available to them. To do that you need to login to your primary site and go to My Sites > Network Admin > Themes.

    On the Network Admin’s themes screen, you will see a list of the currently installed theme on your WordPress multisite. You can make a theme available to other sites by clicking on Enable Network under that theme. Similarly, you can disable a theme by clicking on the Disable Network link under the theme.

    Similarly, you can activate or deactivate a plugin for the whole network from My Sites > Network Admin > Plugins screen. Note that if you have checked the Plugins Menu as available to site admins in the Network Settings, then site administrators can activate or deactivate installed plugins on their own.

    Troubleshooting WordPress Multisite Issues

    Most common issues occur due to incorrect configuration of Wildcard Subdomains. Make sure that your web host supports wildcard subdomains.

    Another common issue is that when using WordPress Multisite with sub-directories, some users are unable to log in to the admin area of their sites after they add the required code in wp-config.php file. To fix this, try replacing the following line in the wp-config.php file:-

    
    define('SUBDOMAIN_INSTALL', false);
    

    with:-

    
    define('SUBDOMAIN_INSTALL', 'false');
    

    If you’re still having problems, feel free to email us to leave a comment below. We sure hope this article helps!

 

Silva Web Designs - Profile

Posted by: Silva Web Designs

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

WooCommerce: Disable Payment Gateway for Specific User Role

You may want to disable payment gateways depending on the user role or user capability. For example, you may want to disable PayPal for ‘user role: subscriber’ or enable a specific gateway for another user role. This can be achieved without a plugin, all you need to do is paste the following code in your functions.php file.


/**
 * Disable Payment Gateway for a Specific User Role | WooCommerce
 */

add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_private' );

 function payment_gateway_disable_private( $available_gateways ) {

    $user = wp_get_current_user();

    if ( isset( $available_gateways['cod'] ) && !is_user_logged_in() || isset( $available_gateways['cod'] ) && in_array('subscriber', $user->roles)  ) {
        unset( $available_gateways['cod'] );
    }

   return $available_gateways;

}

So what the above code will do is remove the ‘Cash On Delivery’ option if you are not logged in, or if you are a user with the ‘Subscriber’ role.

How to Find WooCommerce Payment Gateway ID

If you navigate to WooCommerce –> Settings –> Payments tab, if you inspect the element or view source of this page, you will see a list of codes within a table of all the gateways available on your website as shown in the below screenshot:

What if you want to disable payments for multiple user types?

Okay, we have you covered you here as well. Let’s say you want to disable ‘Stripe’ payment gateway for both the Administrator and Subscriber user but no other user…

What we need to use here is the PHP’s Array Intersect.

Again, this code will get added to your functions.php file and will look something like this:


/**
* Disable Payment Gateway for a Specific User Roles | WooCommerce
*/

function ts_disable_stripe( $available_payment_gateways ) {

//Check whether the available payment gateways have the Stripe option and if the user is not logged in or has the role administrator or subscriber
$user = wp_get_current_user();
$allowed_roles = array(‘administrator’, ‘subscriber’);

if ( isset($available_payment_gateways[‘stripe’]) && (array_intersect($allowed_roles, $user->roles ) || !is_user_logged_in()) ) {

//Remove the stripe payment gateway
unset($available_payment_gateways[‘stripe’]);
}

return $available_payment_gateways;
}

add_filter(‘woocommerce_available_payment_gateways’, ‘ts_disable_stripe’, 90, 1);

Now, the $allowed_roles can list an array of all the users you would like to not display a specific payment gateway for.

Is there a Plugin alternative?

If you don’t feel 100% confident with coding there is a plugin available which offers the same capabilities as the non-plugin method.

There is a plugin called WooCommerce Conditional Payment Gateways to be the most complete when you need to enable/disable payment gateways based on certain criteria. You can create unlimited ‘rules’ and use, for example, cart totals, billing country, shipping country, user role and much more to define which payment gateway shows and which not.

 

Silva Web Designs - Profile

Posted by: Silva Web Designs

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

ACF Repeater Load More using AJAX

Have you ever wanted to show a limited amount of items when using an ACF repeater? Maybe you are using this to display images and to save on load time you only want to show a selective amount instead of loading them all. At the end of the day, having to load fewer images is going to speed up your site right?

In this example, we will show you the basics of adding load more functionality for an ACF repeater field. We are going to display a repeater called gallery and load only 9 items if there are more than 9 items we will display a ‘Load more’ button to programmatically load the rest.

So first of all our markup will look as follows:-


<div id="photo-gallery">
	<div class="row">
		<?php
		if( have_rows('media') ): 
			$total = count(get_field('media'));
			$count = 0;
			$number = 8;					
			while ( have_rows('media') ) : the_row(); ?>						
					<div class="col-md-4 col-sm-6">
						<a class="mag-pop" data-img="<?php the_sub_field('image'); ?>" href="<?php the_sub_field('image'); ?>"><img class="img-gallery" alt="BeWILDerwood Gallery" src="<?php the_sub_field('image'); ?>" /></a>
					</div>
				<?php
				if ($count == $number) {
					// we've shown the number, break out of loop
					break;
				} ?>					
			<?php $count++; endwhile;
		else : endif;
		?>
	</div>
	<a id="gallery-load-more" href="javascript: my_repeater_show_more();" <?php if ($total < $count) { ?> style="display: none;"<?php } ?>><h2 id="title-bg"><span>Load more</span></h2></a>
</div>

As you can see, $number defined the number of repeater items we want to initially display. We use the break; clause to prevent further images from loading.

Now moving on to the JavaScript:-


<script type="text/javascript">
	var my_repeater_field_post_id = <?php echo $post->ID; ?>;
	var my_repeater_field_offset = <?php echo $number + 1; ?>;
	var my_repeater_field_nonce = '<?php echo wp_create_nonce('my_repeater_field_nonce'); ?>';
	var my_repeater_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
	var my_repeater_more = true;
	
	function my_repeater_show_more() {
		
		// make ajax request
		jQuery.post(
			my_repeater_ajax_url, {
				// this is the AJAX action we set up in PHP
				'action': 'my_repeater_show_more',
				'post_id': my_repeater_field_post_id,
				'offset': my_repeater_field_offset,
				'nonce': my_repeater_field_nonce
			},
			function (json) {
				// add content to container
				// this ID must match the containter 
				// you want to append content to
				jQuery('#photo-gallery .row').append(json['content']);
				// update offset
				my_repeater_field_offset = json['offset'];
				// see if there is more, if not then hide the more link
				if (!json['more']) {
					// this ID must match the id of the show more link
					jQuery('#gallery-load-more').css('display', 'none');
				}
			},
			'json'
		);
	}
	
</script>

We’ve added comments within the code so you can see what is happening through the process. Now we need to add the code to the functions.php file to load the additional items.


/**
 * ACF Load More Repeater
*/

// add action for logged in users
add_action('wp_ajax_my_repeater_show_more', 'my_repeater_show_more');
// add action for non logged in users
add_action('wp_ajax_nopriv_my_repeater_show_more', 'my_repeater_show_more');

function my_repeater_show_more() {
	// validate the nonce
	if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'my_repeater_field_nonce')) {
		exit;
	}
	// make sure we have the other values
	if (!isset($_POST['post_id']) || !isset($_POST['offset'])) {
		return;
	}
	$show = 9; // how many more to show
	$start = $_POST['offset'];
	$end = $start+$show;
	$post_id = $_POST['post_id'];
	// use an object buffer to capture the html output
	// alternately you could create a varaible like $html
	// and add the content to this string, but I find
	// object buffers make the code easier to work with
	ob_start();
	if (have_rows('media', $post_id)) {
		$total = count(get_field('media', $post_id));
		$count = 0;
		while (have_rows('media', $post_id)) {
			the_row();
			if ($count < $start) {
				// we have not gotten to where
				// we need to start showing
				// increment count and continue
				$count++;
				continue;
			}
			?>
			<div class="col-md-4 col-sm-6">
				<a class="mag-pop" data-img="<?php the_sub_field('image'); ?>" href="<?php the_sub_field('image'); ?>"><img class="img-gallery" alt="BeWILDerwood Gallery" src="<?php the_sub_field('image'); ?>" /></a>
			</div>
			<?php 
			$count++;
			if ($count == $end) {
				// we have shown the number, break out of loop
				break;
			}
		} // end while have rows
	} // end if have rows
	$content = ob_get_clean();
	// check to see if we have shown the last item
	$more = false;
	if ($total > $count) {
		$more = true;
	}
	// output our 3 values as a json encoded array
	echo json_encode(array('content' => $content, 'more' => $more, 'offset' => $end));
	exit;
} // end function my_repeater_show_more

As you can see above, we are going to load an additional 9 images (or repeater values) on click of the load more button. Once all loaded items have appeared, we are hiding the load more button so that is no longer visible.

And that’s pretty much it! If this has helped you, feel free to drop a comment. If you need any help with this, feel free to get in touch and we’ll be happy to assist you! 🙂

 

Silva Web Designs - Profile

Posted by: Silva Web Designs

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital related. His main expertise is with WordPress, Magento, Shopify as well as many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share