Categories
PHP Wordpress

Insert a content after each post in WordPress

In this article we will learn to insert a content after each post automatically without plugins in wordpress.

One of the greatest things in WordPress, is that we have a lot of tools and plugins to make for us almost anything we could imagine without having to code.

But plugins has some disavadvantages:

    • WordPress is constantly updated, as well as the plugins. This could lead to errors because, sometimes, plugins are abandoned and no more updated and that could cause the plugin doesn´t work properly with lastest wordpress versions, as well as security risks.
    • The updated plugin could have issues that it hadn´t before the update, at least until they are fixed by the plugin developers… if they are.
    • It could have incompatibilities with other installed plugins

To avoid all of these problems, you can always code the funtionality by yourself. Sometimes you will need advanced coding skills but other times almost any person with basic wordpress and php knowledge could do it.

We will append some text to the end of each of your articles, on the main page where all posts are listed, as well as on every post single page.

The first thing is to access through FTP to your theme files (in case you have deployed it, otherwise just go to your local installation). Usually they are on wp_content/themes folder. Of course you will need your FTP access info which can be given to you by your hosting company, so ask them for it.

Inside the theme folder, you can find two files:

  • style.css
  • functions.php

image to show the file we must edit, which is functions.php, to illustrate insert a content after each post in wordpress

By the way,you can see I used a child theme, something I strongly recommend if you customise your theme. Learn more about it here

So, just open your functions.php file .

We will use something called filters to add a function which will add the desired block of code, in this case, to the bottom of each post. But you could add it after each post.

We will add the following code:

 

function auto_insert_after_post($content){

        if (is_single() || is_home()) {

            $contentTop="<div class='post-footer-div'>";

            $content .= $contentTop. '<p><b>If you liked the post or you have seen any error 

            on the info provided on this article, please feel free to contact me

            on <a href="https://www.linkedin.com/in/francisco-javier-prieto-gut/">linked in</a> 

            or <a href="mailto:admin@avanzartewebs.com">by email</a>. 

            I will be glad to talk to you.</b></p>'.$contentBottom;

            $contentBottom="</div>";

        }

        return $content;

    }

    add_filter( 'the_content', 'auto_insert_after_post' );

What this code does is creating a function called auto_insert_after_post .

Inside the function we have a condition based on is_single() and is_home() functions returning values.

  • is_single() will be used to show the content we will create, if we have a single post (so, on each single post page)
  • is_home() will be used to determine if the current page is the blog´s main (home) page. In that case, content will be shown

 

Of course you could use only one of the functions if you want, for example, the code block is only showed on the single post page or the main page.

Inside the IF statement we have 3 variables (you could do it with only the $content variable, but I decided to created 3 variables to add some HTML code, like borders, on what is more for an easier way to understand and manipulate).

The $contentTop and  $contentBottom variables are appended to the $content variable, along with a string which will be the text shown and also some HTML code to include some links and formatting. The $content variable will be returned, so the add_filter() function -which will call this auto_insert_after_post() function we created-, can use it.

Now all we have to do is using the already mentioned add_filter() function, with two parameters

  • the_content is the hook name (as filter is a type of wordpress hook), you also can read more about the_content hook here
  • auto_insert_after_post is the function name we defined before, which will be called by add_filter()

Now you can see how at the end of each one of my posts, the code is created. You also could notice that on the $content variable, one div element has a class called ‘post-footer-div’, which I used to add some styles to the code created with this filter. If you want to create a class and create or change its styles you must do it on the above mentioned style.css file , on wp_content/themes/your-theme-folder.

In my case I used this css code:

.post-footer-div{

    border-top:2px solid black;

    padding-top:20px;

    border-bottom:2px solid black;

}

The padding will create some space between borders and letters

Hope this article is useful to you. In any case, see the result at the bottom of this article 🙂

Maybe you can find more useful info here

Categories
PHP Projects What have I learned?

Building a REST API with SLIM 4 – part 2 – What have I learned? The use of CRON JOBS

Remember you can check and test the project here:

https://rest-api-with-slim-4.avanzartewebs.com/

and see the repo here:

https://github.com/Franweb79/00.rest-api-with-slim-4

On this post, we continue and finish the article and work described here.

To develop this project, I have followed official docs as well as two great tutorials to work with Slim 4

https://odan.github.io/2019/11/05/slim4-tutorial.html

https://medium.com/@sizil.krishna23/creating-a-rest-api-with-slim-php-framework-mercurial-2829cb3f22b3

 

THINGS I HAVE LEARNED

-First of all, I had to work with composer, which is a PHP package manager similar to npm for Javascript. Never worked with it.

I also have learnt some things I consider good practices or at least a better way to do things than I was doing before:

 

-The attribute names on forms should not be composed of many words without separation. For example is better to avoid mistypings and confussions:

login_checkbox_name

than

loginCheckBoxName

So it would be, for example:

<input type=”checkbox” name=” login_checkbox_name”>

Also never use spaces, can lead to errors when validating

 

-I am very concerned about security. As I had to store user´s session  I have investigated a lot regarding cookies and other options to store and remember user sessions.

 

I realized that storing sensitive data like user´s hashed password to remember the session  on cookies is not secure (when you are nov ice is usually to make it that way). So, after seeing disvantages of options like Local Storage which can be easily attacked through javascript and XSS injections, I decided to use a session token which will generate a random code when user wants to remember session and which will be unique for that only user and session.

 

-I have also realized that, although learning to validate a form with raw PHP is essential, if you want to save time, sometimes you must use some of those libraries, specially if you have a project with a given deadline. It has disvantages like relying on an external library to do things that could entirely be done by yourself, but nowadays is necessary.

ln this case, I researched and used valitron to validate the form.

https://github.com/vlucas/valitron

 

-Maybe the most important among all the things listed in this post that I noticed, is the importance of trying to write clear, proper comments.  Benefits:

  • A good and clear structure, will be useful not only for future programmers but for yourself in the future. How many times happened that you check a code some years or even months later, and you don´t know why or how you did something? Good comments will avoid it. Make comments as if you don´t know how to code. Don´t take things for granted. Some programmers think commenting code is a sign of unclean code which doesn´t speaks by itself. As I pointed out, I personally find you could have problems to understand your own code in the future and, also, I find it disrespectful for new developers which could join the project later, if you work on a team. A team is supposed to be working for a common goal, and we must make things easy to each other. For me the willing to help, and the wish to learn are even more important than coding skills to achieve success on a company.
  • Another implicit advantage will be you will save a lot of time later, because you won´t have to clean so much For sure you can do a bulk deleting action with some IDEs like VS Code, if you have to delete all the commented “var_dump()” or “die()” you left everywhere; but it vcould lead to errors if you delete something should not be deleted with that bulk deletion.So, I have read some good articles and spent a lot of time  improving comments. I know it is far from being perfect but I hope it is clear enough (I wait for your advices anyway).
  • Also I tried to present a professional and clear readme.md file on the project.  Proper work with markdown (md) files (remember you can see it on my GitHub repository), can help you look like a real developer which cares about project´s usage.https://www.markdownguide.org/basic-syntax/.Maybe for next project I will try the flavored Github markdown too.

-Also regarding security and usage, I find important that recruiters or potential employers are allowed to actively test my work; that means they can create users, upload images…

In order they can test my projects on a more secure way, I started to use MySQL scheduled tasks and/ or CRON jobs.

That allow me to reset the app´s database on a regular basis (daily, monthly…), so we are sure it doesn´t matter what the user do; the app will be restored with the demo data I want it  to include and show.

Usually it is done with MySQL scheduled jobs, but sometimes it is not possible, like it actuallyu happened to me on this project. Reason is, my hosting provider uses a shared web server, and for security reasons, scheduled tasks are only allowed for a super user, and a super user would compromise the safety of other databases hosted by other users on that hosting.

To solve that, they allow to execute those scheduled jobs through CRON JOBS , which are linux commands which will work on a server going under that Operative System (for example, with Apache). This way you can create scheduled jobs without having too many, risky privileges.

 

– I have noticed (or better said, remembered) the importance of always having PAPER AND PEN with you.

Someone told me about that at the beginning of my career, but  many times we don’t realize due to pressure, and sometimes we don´t see we can save a lot of time if we stop coding and start to analyse a problem with a paper and a pen.

For example, on this project I had a problem to show the errors array provided by valitron library. I thought it would return an array with each error being an index of that array; but after struggling with some problems to properly show those errors,  when I made a print of the array with print_r(), I saw it was something different

array-error-valitron

So, with the little help of a paper and a pen to see it more structured, I saw the errors array it was actually an array of arrays, being each error an array itself, so I had to iterate like the old, basic matrix (with two foreach loops).

array-error-2

 

-Another thing I find a good practice is that a method should do only what it says it does.

If your method is called “insertUser()” your method should only insert that user. Connection to Database should be for example another method which would implement the connection logic, and would be called inside “insertUser()”

 

-More about security basics: Using PHP PDO statements will improve our code´s security and can avoid SQL injections.

https://www.w3schools.com/php/php_mysql_prepared_statements.asp

 

-And last but not least, maybe is also a good practice if we obfuscate your Javascript files to make things a little harder for potencial attackers. Specially if for example you use AJAX  techniques to retrieve data from a database.

You have a good free tool to obfuscate yourt code here:

https://obfuscator.io/

 

So I can say, developing this project has been extremely productive to me, because I have remembered and learned many useful things which will help me to be a better developer.

Development has gone slower than I would like because at the same time I am updating my Angular and Javascript skills, as well as digging a bit into the Reactive Programming paradigm which is so usual and essential today (including the mentioned Angular framework).

Also I am learning swedish and learning to play guitar as well as giving sports and mindfulness the importance in life it should have for every of us. Even as developers such things can be more helpful than we could think to be more productive. That´s why I mention it: I learned the importance of taking care about your body and mind. I will finish with a good reading about it:

https://www.activenorfolk.org/2021/05/mental-benefits-of-sport/

 

Categories
PHP Projects What have I learned?

Building a REST API with SLIM 4: Part 1

Before I had to be full.time dedicated to take care about my mother, I had some projects to include on my portfolio.

One of them was a REST API made with PHP and SLIM2. I used this API as a mock backend for many applications, like my car selling fake app. Here you can see the back-end and fron-end code (made with Angular 6) of that app

https://github.com/Franweb79/carsapp-frontend

https://github.com/Franweb79/carsapp-backend

Also you can see the project working here ( you will find a 403 Forbidden response, but ask me and I will give you an access to check). The reason that is is closed is that you can “play” with it: change or upload pictures… and I don´t want that to be done by anyone on the internet, of course 🙂

When I wanted to code it again, to refresh my knowledge, I noticed there were a lot of differences between SLIM 2 and the actual SLIM 4. Also, as the old version was made following a course, I wanted to make again from scratch,  then I can feel the API is “more mine”.

SLIM is a PHP framework, very useful to quickly create apps or APIs. Maybe it is not so powerful as Laravel, for example, but for people like me, which are more focused on Javascript and frameworks based on it, like Angular or React, SLIM can be a good solution when we want to do things like this.

As documentation is maybe not as clear for a noob asd it should be, I will start a series of articles to describe how I made the API and what worked for me.

But the first thing will be to sync GIT with my GITHUB and my IDE (Visual Studio Code), to commit the changes easily. That will be the next article. Of course you don´t need to do that but I think is a good moment to explain the very basics I know about it.