Using multiple if else to check for content and member status - php

I am trying to check if a user is logged in as a member and also if a meta field in a WordPress custom post type has content and then need to display content based on 4 possible outcomes. I am using WordPress membership plugin woomembers
user is logged in as a member and content exists - display content
user is logged in as a member and content field is empty - display nothing
user is not a member and content exists - display some content and sign up
user is not a member and no content exists - display sign up
I have this code partly working but can't get item 3 to work?
The code I have is:
<?php $meta_content_field = get_post_meta($post->ID, "meta-content-field",
$single = true);
if (wc_memberships_get_user_active_memberships() &&
$meta_lighting_diagram != '') {
// Active member and has content- do something here
?>
html content here
<?php
} elseif (wc_memberships_get_user_active_memberships() &&
empty($meta_content_field) ) {
// No content but active member - do something here
echo "No content but active member";
} elseif ( ! empty( wc_memberships_get_user_active_memberships() ) &&
($meta_content_field) ) {
// content but non-member - do something here - this is not working?
echo "Has content but NOT active member";
} else {
// Non-member - do something here ?>
html content here
<?php }
?>

Your loop is wrong. First check should be member or not.
if ( $member) {
// do something for the member
} else {
// do something for the non-member
}
Then you want to check whether or not there is content.
Do this within the if-loop
if ( $member ) {
// do something for the member
if ( $content ) {
// member and content
} else {
// member no content
}
} else {
// do something for the non-member
if ( $content ) {
// non-member and content
} else {
// non-member no content
}
}
a maybe even better approach would be to use switch(). Could look like this:
$status = '';
if ( $member ) $status = 'member';
else $status = 'nonmember';
if ( $content ) $status .= 'content';
else $status .= 'nocontent';
switch ( $status ) {
case 'membercontent':
// do something
break;
case 'membernocontent':
// do something
break;
case 'nonmembercontent':
// do something
break;
case 'nonmembernocontent':
// do something
break;
}
This can be simplified (shortened) in combination with default:.

Related

Generate meta page title exactly as on h1 tag

Site based on Joomla. I have many pages where h1 header is mentioned as product detail and displayed based on product details through PHP. There are 2 files: default.php and view.html.php.
default.php :
<h1>Used <?php echo $this->CatName; ?> <?php echo $this->prodDet->prod_name;?> Toy for Sale </h1>
This correctly display the h1 tag. I want to generate meta title of the page and use this h1 output as generated in view.html.php. This line defines the title of the page :
$this->document->setTitle($title);
And this line defines header h1 :
"{$this->item->heading}";
Complete code :
protected function _prepareDocument()
{
$app = JFactory::getApplication();
$menus = $app->getMenu();
$title = null;
// Because the application sets a default page title,
// We need to get it from the menu item itself
$menu = $menus->getActive();
if ($menu)
{
$this->params->def('page_heading', $this->params->get('page_title', $menu->title));
}
else
{
$this->params->def('page_heading', JText::_('COM_USEDCAR_DEFAULT_PAGE_TITLE'));
}
$title = $this->params->get('page_title', '');
if (empty($title))
{
$title = $app->get('sitename');
}
elseif ($app->get('sitename_pagetitles', 0) == 1)
{
$title = JText::sprintf('JPAGETITLE', $app->get('sitename'), $title);
}
elseif ($app->get('sitename_pagetitles', 0) == 2)
{
$title = JText::sprintf('JPAGETITLE', $title, $app->get('sitename'));
}
$title = "{$this->item->heading}";
$this->document->setTitle($title);
if ($this->params->get('menu-meta_description'))
{
$this->document->setDescription($this->params->get('menu-meta_description'));
}
if ($this->params->get('menu-meta_keywords'))
{
$this->document->setMetadata('keywords', $this->params->get('menu-meta_keywords'));
}
if ($this->params->get('robots'))
{
$this->document->setMetadata('robots', $this->params->get('robots'));
}
}
Output in title tag is heading. How to put this h1 tag output instead of $title?
Here's what the title portion of your code does:
// getting title from params
$title = $this->params->get('page_title', '');
// trying to get it right
if (empty($title))
{
$title = $app->get('sitename');
}
elseif ($app->get('sitename_pagetitles', 0) == 1)
{
$title = JText::sprintf('JPAGETITLE', $app->get('sitename'), $title);
}
elseif ($app->get('sitename_pagetitles', 0) == 2)
{
$title = JText::sprintf('JPAGETITLE', $title, $app->get('sitename'));
}
// overwrite everything above with some value, making above code useless
$title = "{$this->item->heading}";
$this->document->setTitle($title);
I might be wrong but if I recall correctly, if a value doesn't exist it will return the variable name when cast into a string. Here "heading" might be empty.
You might want to change your code to something like this:
[...]
if(!title){
if(property_exists($this, 'item') && property_exists($this->item, 'heading') && $this->item->heading){
$title = $this->item->heading;
} else {
$title = sprintf('Used %s %s Toy for Sale' , $this->CatName, $this->prodDet->prod_name);
}
}
$this->document->setTitle($title);
You might as well like to save the title to session and reuse it everywhere:
[...]
$this->document->setTitle($title);
// save title to session
$_SESSION['page_title'] = $title;
and update the previous loop:
// getting title from params
$title = (isset($_SESSION['page_title']) && $_SESSION['page_title'])? $_SESSION['page_title'] : $this->params->get('page_title', '');
if (empty($title)){
[...]
Full code would be something like that:
[...]
session_id() || session_start();
$title = (isset($_SESSION['page_title']) && $_SESSION['page_title'])? $_SESSION['page_title'] : $this->params->get('page_title', '');
if(!title){
if(property_exists($this, 'item') && property_exists($this->item, 'heading') && $this->item->heading){
$title = $this->item->heading;
} else {
$title = sprintf('Used %s %s Toy for Sale' , $this->CatName, $this->prodDet->prod_name);
}
}
if (empty($title))
{
$title = $app->get('sitename');
}
elseif ($app->get('sitename_pagetitles', 0) == 1)
{
$title = JText::sprintf('JPAGETITLE', $app->get('sitename'), $title);
}
elseif ($app->get('sitename_pagetitles', 0) == 2)
{
$title = JText::sprintf('JPAGETITLE', $title, $app->get('sitename'));
}
$_SESSION['page_title'] = $title;
$this->document->setTitle($title);
[...]
You might as well just ditch everything and go like that if you'd like:
[...]
$title = $this->params->get('page_title', '');
if(!title){
if(property_exists($this, 'item') && property_exists($this->item, 'heading') && $this->item->heading) {
$title = $this->item->heading;
} elseif(
property_exists($this, 'CatName') &&
property_exists($this, 'prodDet') &&
property_exists($$this->prodDet, 'prod_name') &&
$this->CatName &&
$this->prodDet->prod_name
){
$title = sprintf('Used %s %s Toy for Sale' , $this->CatName, $this->prodDet->prod_name);
} else {
$title = $app->get('sitename');
}
}
$this->document->setTitle($title);
[...]
Code is untested but it should put you on the right track :)
Why don't you just send your h1 content to your php-document as GET parameter and then just output the it using echo inside the title tag? Unless you avoid dinamic echoing, this could be a fine solution for outputting text as title.
I would abstract away the logic of constructing the title/header to some function and then use this function to construct the title in both places.
function constructTitle($catName, $prodName) {
return "Used {$catName} {$prodName} Toy for Sale";
}
...
[in default.php]
<h1><?php echo constructTitle($this->CatName, $this->prodDet->prod_name); ?></h1>
[in view.html.php]
$this->document->setTitle(constructTitle(..., ...));
This allows you to have a single point to format your title while using it in several places.
The function needs to, obviously, be place in such position so that it can be accessed in both places and you need to have some way to get category name and product name in view.html.php. Im not familiar enough with joomla to know these things.
Edit:
To clarify, there is no real way to "extract" the title from the default.php as it is dynamic. You would need to process the php file then maybe you could do some regex magic, but this is in no way the proper solution to the problem.
you can just send your h1 content to your php-document as GET parameter and then output the it using echo in the title tag? Unless you avoid dynamic echoing,it would work.

How to define condition based on get url value

When a user clicks on "List View" link then I want to show them the "List View" HTML and when they click on "Grid View" I want to show "Grid View" HTML.
I've defined the following links to click-
List View <br>
Grid View
Then I defined the following condition with PHP get method to show user the desired output-
<?php
if( isset( $_GET['view'] ) == 'list' ){
echo "This is List view";
}else if( isset($_GET['view'] ) == 'grid' ){
echo "This is Grid view";
}
This condition is not working. If I change "view" to "view_1" and "view_2" from URL then my condition is working as well.
<?php
if( isset( $_GET['view_1'] ) == 'list' ){
echo "This is List view";
}else if( isset($_GET['view_2'] ) == 'grid' ){
echo "This is Grid view";
}
?>
<br>
List View <br>
Grid View
But I don't want to change the "view" key. I just want to keep the same key and different value for both URL to do the conditional statement.
Is it possible?
isset() only checks if a variable exists and isn't null and returns a boolean (true/false).
To check the value, you first need to check if it exists (isset) and then check the value, like this::
if (isset($_GET['view']) && $_GET['view'] == 'list') {
// your code here.
}
You can read more here: http://php.net/manual/en/function.isset.php
Alternative
If you want to make your code and conditions slightly more readable, you could to this:
// Get the value of $_GET['view'] once, if it exists (pre PHP 7)
$view = isset($_GET['view']) ? $_GET['view'] : null;
// PHP 7.x (new shorter syntax for the above)
$view = $_GET['view'] ?? null;
if ($view == 'list') {
// your code
}
Did you try like this..
if(isset($_GET['view']))
{
if($_GET['view'] == 'list')
{
//code here
}
elseif ($_GET['view'] == 'grid')
{
//code here
}
}

Adding schema to meta <head>-tag: wordpress

I am trying to put this (below code) to my wordpress header but when i save and load site on browser it does not show up. I have seen this schema practice on some wordpress themes so it should work. Does anyone have advice? Is it some automatic wordpress function that changes this.
<head itemscope="" itemtype="http://schema.org/WebSite">
do it like this on your header.php
<html <?php html_tag_schema(); ?> <?php language_attributes(); ?>>
and you need to write the function html_tag_schema() now. write the below function on your active theme's functions.php
function html_tag_schema()
{
$schema = 'http://schema.org/';
// Is single post
if(is_single())
{
$type = "Article";
}
// Contact form page ID
else if( is_page(1) )
{
$type = 'ContactPage';
}
// Is author page
elseif( is_author() )
{
$type = 'ProfilePage';
}
// Is search results page
elseif( is_search() )
{
$type = 'SearchResultsPage';
}
// Is of movie post type
elseif(is_singular('movies'))
{
$type = 'Movie';
}
// Is of book post type
elseif(is_singular('books'))
{
$type = 'Book';
}
else
{
$type = 'WebPage';
}
echo 'itemscope="itemscope" itemtype="' . $schema . $type . '"';
}
I hope this one solves your problem

Multiple IF php with 2 else statements

I am trying to use the following code to 1st check if a user has a certain member level, then if they have a blog on the wp network. If they pass both those checks then a link is echoed, if they dont pass the first if check then another link is echoed. Also though, I am trying to check if they pass the first if but fail the second one then a different link is echoed. Here's the code I have now -
<?php
if(pmpro_hasMembershipLevel(array(2,4))) {
if(current_user_can( 'edit_posts' )) {
global $current_user;
$blogs = get_blogs_of_user( $current_user->id );
if($blogs) {
foreach ( $blogs as $blog ) {
if($blog->userblog_id != 1) {
echo '<li>My Site</li>';
} else {
echo '<li>Register your Site</li>';
}
}
}
}
} else {
echo '<li>UPGRADE</li>';
}
?>
The code above echoes the register link when its suppose to but when the user has a blog, the register link shouldnt show but now it shows next to my site link. Any ideas?
EDIT
Free user sees a UPGRADE link
Premium Users without site see a REGISTER Link ( the membership array of 2,4 are the levels they have to be either one of )
Premium members with a site will see the MY SITE link.
EDIT
I was able to use the print_r and on the page where it's suppose to echo the register link -- Array ( [1] => stdClass Object ( [userblog_id] => 1 [blogname] => mysite.com [domain] => mysite.com [path] => / [site_id] => 1 [siteurl] => https://mysite.com [archived] => 0 [spam] => 0 [deleted] => 0 ) )
Looking at the Wordpress MU documentation, I would guess that the get_blogs_of_user always returns an array, so checking on the value of $blogs exists is always going to return true. In the following code, I suggest replacing the simple check on the existence of a value with a check to determine if the returned value is an array and, if so, whether it has elements or not:
<?php
if (pmpro_hasMembershipLevel(array(2,4))) {
if (current_user_can( 'edit_posts' )) :
global $current_user;
$blogs = get_blogs_of_user( $current_user->id );
/*Check if we got an array back and, if so,
check if it has elements*/
if ( is_array($blogs) && ( count($blogs) > 0 ) ) {
foreach ( $blogs as $blog ) :
if($blog->userblog_id != 1) {
echo '<li><a href="http://' . $blog->domain
. $blog->path
.'wp-admin/">My Site</a></li>';
}
endforeach; // end foreach loop
} else {
echo 'Register your Site';
} // end if $blogs
endif; // endif current_user_can
} else {
?>
<div>UPGRADE</div>
<?php
}
?>
Try this :
<?php if(pmpro_hasMembershipLevel(array(2,4))) {
if(current_user_can( 'edit_posts' )) {
global $current_user;
$blogs = get_blogs_of_user( $current_user->id );
if($blogs) {
foreach ( $blogs as $blog ) {
if($blog->userblog_id != 1) {
echo '<li>My Site</li>';
}
}
} else {
echo 'Register your Site';
}
}
} else { ?>
<div>UPGRADE</div>
<?php } ?>
Give this one a shot. Even if it doesn't work in its current state, it should be easier to see the logic and figure out whats not working properly.
EDIT: Shamelessly stole #JustinPearce's method of checking if the user has a blog from his answer
<?php
global $current_user;
$blogs = get_blogs_of_user( $current_user->id );
// print_r($blogs);
$has_membership_level = pmpro_hasMembershipLevel(array(2,4));
$has_blog = ( current_user_can('edit_posts') && is_array($blogs) && count($blogs) > 0 );
$registerLink = 'Register your Site';
$upgradeLink = '<div>UPGRADE</div>';
function echoBlogLinks($blogs) {
echo '<ul>';
foreach ( $blogs as $blog ) {
if($blog->userblog_id != 1) {
echo '<li>My Site</li>';
}
}
echo '</ul>';
}
if ($has_membership_level) {
if ($has_blog) {
echoBlogLinks($blogs);
} else {
echo $registerLink;
}
} else {
echo $upgradeLink;
}

PHP form requires to be submitted twice

I'm writing an application that allows users to upload reference letters for potential employees.
Every reference is sent an email containing a unique string at the end of the url. So, for example, an address would look similar to: www.mywebaddress?url=503241a20b5085_18720621.
To determine if the unique string is valid (i.e. exists in the database) I need to do a query search. However, when a reference attempts to access the URL he needs to answer a security question. So, I also need to check if the answer is valid, if he has previously uploaded, etc to determine what page to redirect him to.
But because of the query, my code requires the user to click "Submit" twice. This is really annoying, but I'm not sure how to fix it.
Here is a relevant excerpt of my code:
if ( isset ($_GET['url']) ) {
$query = "SELECT * FROM ref_info WHERE url='" . $_GET['url'] . "'";
$result = $db->execute($query);
if ( empty ($result) ) {
//error message
} else {
$url = $_GET['url'];
if ( $_SESSION['validated'] ) {
if ( $result[0]['uploaded'] ==1 ) {
$_SESSION['uploaded'] =true;
} else {
$_SESSION['uploaded'] =false;
}
include_once("process_upload.php");
} else {
if ( empty($result[0]['answer']) ) {
include_once("security.php");
} else {
include_once("security_check.php");
}
}
}
}
Is there anything I can do so that the form only needs to be submitted once?
Thanks in advance for any suggestions!!
if ( isset ($_GET['url']) ) {
$query = "SELECT * FROM ref_info WHERE url='" . $_GET['url'] . "'"; //that is really not secure. Take a look at mysql_real_escape_string or something like that in yor $db
$result = $db->execute($query);
if ( empty ($result) ) {
//error message
} else {
$url = $_GET['url'];
if (empty($result[0]['answer']) ) { // page is just opened,form is not yet submitted - ask sequrity question
include_once("security.php");
} else { //oh. Submit is done - let me check if it is Ok
include_once("security_check.php");
}
if ( $_SESSION['validated'] ) { //validation is Ok? Yeah. Answer is not posted yet, so validation fails and we do nothing. Just show a form with a question
if ( $result[0]['uploaded'] ==1 ) {
$_SESSION['uploaded'] =true;
} else {
$_SESSION['uploaded'] =false;
}
include_once("process_upload.php");
}
}
}

Categories