Wordpress Delay content being published to non-members - php

I have a wordpress site that uses the WPMU Membership plugin. I want to add code to my template that displays a new post to members 5 days before it is shown to non-members.
Something like this:
if (current_user_on_level(17) && CODE TO DETERMINE IF POST IS LESS THAN 5 DAYS OLD) {
echo POST CONTENT;
}
else {
echo 'Info not available yet';
}
;
What code would I use to determine whether the published post is less than 5 days old??

I figured out the answer. First had to convert the post time to a UNIX code using this code:
(True sets it to UNIX epoch time rather than set to local time zone)
Then I used this code to get the UNIX time 5 days ago
strtotime("-5 day")
Put the two together with an if statement that displays the content or if it's not time it displays a message that the content isn't available yet.
<?php
$post_timestamp = get_post_time('U', true);
if (current_user_on_level(17) && $post_timestamp <= strtotime("-1 day"))
{
get_template_part( 'content', get_post_format() );
}
else {
echo 'No post available yet <br />';
}?>
The only issue with this is that because my posts are ordered in chronological order, the top of my blog is filled with the line "No post available yet". Can anyone think of how I can get these statements to sit at the bottom?

Related

Wordpress : How to hide page depend on time in php

I'm looking to hide some page of a website between 10 AM AND 20 PM each day
I add the code below on the file function.php
<?php
if (date('H')>10 && date('H')<20{echo 'url page';}
?>
This code breaks the website. I'm looking for the correct code to add.
Besides syntax errors mentioned in comments, I guess you need to check whether it is the particular page you need to lock down, so you won't do that to the entire site. If that page is some WordPress post, you can block access by post ID, like this:
function blockAccessFromPost($post) {
$post_id = $post->ID;
$hours = intval(date('H'));
if ($hours >= 9 && $hours < 20 && $post_id === 1123) {
echo 'Please wait...';
exit; // exit is required so no further code is executed.
}
}
add_action('the_post', 'blockAccessFromPost');
In case if you don't know where to find the post/page id, here's the article.
The previous version of the answer was wrong, because it was unable to get access to the post data right away, WordPress was not initalized. the_post hook helps to execute the code in the moment when current post data has just loaded.
Still the same, I really don't know with, your code look perfect. When I use it, the post disappear in the list and I can see wirtten "Please wait...1391". But widget footer etc disappear.
I post you back the code below to be sure to use it well..
function blockAccessFromPost($post) {
$post_id = $post->ID;
$hours = intval(date('H'));
if ($hours >= 9 && $hours < 20 && $post_id === 1391) {
echo 'Please wait...';
echo $post->ID;
exit; // exit is required so no further code is executed.
}
return $post;}
add_action('the_post', 'blockAccessFromPost');
?>```

How can I query mysql table and display result using php conditional statements

I want to show user that he has vaccinated his goat after successfully payment confirmation.
Here is what I tried:
<?php
$treatperiod1=$product_row['treat1'];
$currentDate = date("Y-m-d");
$totalDays = $treatperiod1;
$usedDays = round(abs(strtotime($currentDate)-strtotime($orderdate))/60/60/24);
$remainingDays = $totalDays-$usedDays;
if($remainingDays==0) {
echo "<a target = '_blank' href ='product_addon.php?treatp=$treatperiod1' class='btn btn-success'><i class='fa fa-pencil'></i>Vaccinate Gaoat</a>";
} elseif($remainingDays==$treatperiod1) {
echo 'Vaccinated';
} else {
echo $remainingDays.' Days Left';
}
?>
I have displayed remaining days for vaccination intervals I want to also display 'Vaccinated' if user payment for vaccination is confirmed. $product_row['treat1']; is a column where the number of days for vaccination is specified. order_details is a table for orders with column confirm for confirmed orders.
Goat Vaccination:
Because Goats don't get Autism
Please read how to use PHP DateTime objects because they will make your life a lot easier on this project.
I will rewrite your code and then tell you what the new code does:
//establish DateTime objects.
$currentDate = new DateTime(); //now.
$orderDate = new DateTime($orderdate); //$orderdate format Y-m-d
//Establish how may days since order date and today.
$difference = $orderDate->diff($currentDate);
$usedDays = $difference->days;
/***
Total Period paid for,
in days, integer.
$product_row['treat1'];
***/
$remainingDays = $product_row['treat1'] - $usedDays;
//Returns an integer value of remaining days.
if($remainingDays < 1) {
echo "<a target = '_blank'
href ='product_addon.php?treatp=".$treatperiod1."'>
Vaccinate Goat</a>";
} elseif($remainingDays==$product_row['treat1']) {
//This will only fire if the goat was vaccinated TODAY.
echo 'Vaccinated';
} else {
echo 'Vaccinated:' .$remainingDays.' Days Left';
}
Hopefully with the help of the link above you should be able to see the basics of what I wrote out for you.
Some notes:
Stop making variables that are simply copies of other variables, it's inefficient and confusing.
(Try to) Stop sending data to new PHP pages as GET URL values such as /newpage.php?treatp=".$var.". This is very probably very insecure.
A more specific answer will need a full explanation from you of your MySQL tables, if nessecary please edit your question and add them.
Try and move away from using timestamps and treating timestamp variables as mathematical entities, and use the DateTime object instead.
Really, to determine if a payment is made you should have a payment date value in your database (set when a payment is successful) and simply compare this date to the value of the integer of the number of days payment covers, using the ->diff() method illustrated above.
Further information on Goat Vaccinations

Change order of elements in query results array

[edited] I need to display posts from database sorted in a kinda specific way.
There is a page which at set time interval query database via ajax to pull 180 latest post. Each post in db has column "source" which can be "instagram" or "twitter". Ajax returns 30 sets (or less) x 6 posts each (less if there is not enough posts). Than with help of js all sets are hidden and only one set (6 posts) is displayed at a time. After few seconds set is hidden and next one is shown. Think of it like a typical slideshow but with posts instead of images on infinite loop.
At the begining it wasn't important what kind of post were in sets. It could be all 6 posts from twitter or instagram or mixed. But as usual when project was scheduled to finish, I was asked to change the way sets are generated. Now client wants to have only 2 types of sets with posts in particular order (described below).
So my question is how change this (simplified example from my ajax file):
DB details for ref.: table POSTS: id / source / user / date etc.
$sql="SELECT * FROM posts ORDER BY id DESC LIMIT 180";
...
$stmt->setFetchMode(PDO::FETCH_OBJ);
$set=1;
while($row = $stmt->fetch()) {
if($set==1){
echo '<!--start set--><div class="set">';
}
if($row->source="twitter"){
echo '<div class="post twitter">';
echo '{all stuff related to this twitter post}';
echo '</div>';
} else if($row->source="instagram") {
echo '<div class="post instagram">';
echo '{all stuff related to this instagram post}';
echo '</div>';
}
if($set==6) {
echo '</div> <!--//END set-->';
$set=0;
}
}
$set++
}
into something what let me generate those 30 sets but with posts distributed among them using this pattern:
<!--First set should has post in order: --
<div class="set>
<div class="post twitter">{stuff}</div> {instagram post} {instagram post}
{instagram post}{instagram post}{twitter post}
</div> <!--//END set-->
<!--Second set order:-->
<div class="set">
{instagram} {instagram} {twitter}
{twitter} {instagram} {instagram}
</div>
etc.
Of course there is no guarantee that there would be enough post to create all 30 sets with those patterns so I need to create as many sets following those two patterns and leftovers put in sets as before simply in order they are pulled from db.
Thats all.
Thanks in advance for any suggestions / ready solutions ;) etc.
You could try something with a split between the two kind of posts using array_filter.
$posts = $stmt->fetchAll();
$twitterPosts = array_filter($posts, function($post){
return $post->source == "twitter";
});
$instagramPosts = array_filter($posts, function($post){
return $post->source == "instagram";
});
$set=1;
while(!empty($twitterPosts) && !empty($instagramPosts))
{
if($set%2 == 1)
{
$instagramPost1 = array_shift($instagramPosts);
$instagramPost2 = array_shift($instagramPosts);
$twitterPost1 = array_shift($twitterPosts);
}
else
{
$instagramPost1 = array_shift($instagramPosts);
$twitterPost1 = array_shift($twitterPosts);
$twitterPost2 = array_shift($twitterPosts);
}
/* display them */
if($set==6) {//your condition
echo '</div> <!--//END set-->';
$set=0;
}
$set++;
}
/* now one of them is empty, you can just display the other one */
if(!empty($twitterPosts))
/* Display all remaining twitter posts */
elseif(!empty($instagramPosts))
/* Display all remaining instagram posts */
Of course you should add validation that there is still something in the array between 2 array_shift.
I hope this helps !
EDIT : sorry I missed the condition for only 3 item per row, adding it now.

Link visible between certain times

I would like someone to help me please.
I need a link to be visible between certain times say 6pm & 1am in the evenings. Clients that are registered on my site can change the times of store opening and closing times within their admin panel and it connects to a table in a database.
The link needs to only be visible during specified times that the client decides via their control panel. Out side of these hours the link is hidden/not visible and not clickable.
So this needs to call/echo times from database table for each customer.
any help would be great.
many thanks
Mark
You could use something like...
// check if the date (current hour) is between two times,
// if it is, assign the link to $link, else assign nothing to $link
$link = date('H') >= 6 && date('H') <= 20 ? 'Link' : ''; // replace hardcoded hours with vars if needed
echo $link;
try this:
// Assuming $userMin and $userMax are the users specified times
$time = date( 'H' );
if( $time > $userMin && $time < $userMax ) {
echo "<a href='linkUrl'>Description</a>";
}

Disable PHP count?

So, I am trying to modify a piece of code that I have, it is a calendar that is used for taking reservations. I am posting events on the calendar that users will be able to book by clicking on the link on any given day. It currently allows me to only post 2 events for booking, on any given day. These 2 cannot be at the exact same time. I want to change that, I need it to be able to post multiple spots available at the exact same time. For example, if it is a martial arts class and there are 10 open spots, it should show 10 spots available at the same time of day... You get the point...
I believe this is what is preventing me from achieving that, but im not certain...
Any help is much appreciated. Thanks is advance.
<script>
<?php
if($numslots>0) {
?>
alert('<?php echo $numslots; ?> slots added');
<?php
} else if($numslots == -1) {
?>
alert('Days selected are holidays. Cannot make these changes');
<?php
} else {
?>
alert('Duplicate slots. Cannot make these changes');
<?php
}
?>
document.location.href="calendar_manage.php?calendar_id=<?php echo $_GET["calendar_id"]; ?>&ref=slots";
</script>
In your example, where you have ten slots available for one time, you need to populate a new variable.. lets call it $available_slots.. you need to populate this with the number of slots, in this case ten. So you would end up with ...
$available_slots = 10;
if($numslots<$available_slots) {
?>
alert('<?php echo $numslots; ?> slots added');
<?php
} else if($numslots == -1) {
etc...
Notice the first if condition.. we now check if $numslots is less than $available_slots, rather than greater than zero.

Categories