WordPress - PHP conditional logic - php

I have a really simple question about PHP conditional logic. I have some code where I want to load a different header file based on the post category type. The code below works:
if(in_category('news')) {
get_header('tertiary');
}
elseif(in_category('events')) {
get_header('tertiary');
}
else {
get_header('secondary');
}
But when I try to simplify the code to:
if(in_category('news' || 'events)) {
get_header('tertiary');
}
else {
get_header('secondary');
}
The tertiary header file for the events is not loading, it is showing the secondary header file. I'm using similar code elsewhere in my theme and it is working with no issues. So I'm not sure why it is not working here. I'm not getting an errors in my PHP console.

There may be two ways you can do this. Check in_category individually (this will always work)
if(in_category('news') || in_category('events')) {
Or in_category can take an array, in some versions of Wordpress:
if(in_category(['news', 'events'])) {

You need to read the documentation and instead of
if(in_category('news' || 'events)) {
...
do
if(in_category(['news', 'events'])) {
...

You need to read the documentation
if ( in_category( Array( 'news', 'events' ) ) ) {
get_header('tertiary');
} else {
get_header('secondary');
}

Related

if title contains string 'aaa','bbb' or ,'ccc' replace field {category[1}

Hello gods of Stackoverflow,
Now i hate to be "that guy" who didnt search properly but i am running into a problem that i need a fix for and can't find a solution i can work with because of my lack in coding skills, my knowledge barely tickles the surface.
Here's the thing.
I am using a tool to import feeds into my website (WP all Import) as woocommerceproducts. But in the categorization the feed suppliers made errors which i want to tackle without emailing them everytime i stumble upon one.
i.e: the title contains words like satchel, bag, clutch etc but the product is categorized as 'jewellery > earrings' in the CSV or XML.
The import tool will ask me where to find the product category, i point it to the node {category[1]}
But when the category is missing or faulty i want it to check the title for certain words, and if present change the value of it to that found word.
something like:
[if ({title[1]}contains "satchel") {
category = "bags > satchel",
} else if ({title[1]} contains clutch) {
category = "bags > clutch",
} else {
category = {sub_category[1]} #the normal value if nothing was found
}]
I just can't find the pieces to put the formatting together. I might need to work towards a function that i could expand to generate categories based solely out of presence of certain words in the title but maybe when i get better that would be an option.
I hope i was able to provide a clear view on the problem. The "[ ]" is there because thats how the plugin wants code to be entered instead of a {fieldname[1]}, another example below:
The following was an example of a problem i was able to fix:
i needed to replace values like "0/3months/1/2months" to "0-3 months/1-2months" before i replaced the slash"/" with a pipe"|" for wordpress to recognize it as a seperate value.
[str_replace("/","|",
str_replace("0/3","0-3",
str_replace("1/2","1-2",
str_replace("3/6","3-6",{size[1]}))))]
The fields can also be used to call functions but only in the 'pro' version of the plugin.
Any help is very much appreciated, thanks in advance.
You could use strpos.
Example:
if (strpos($title, "satchel") !== false) {
$category = "bags > satchel";
}
So after an afternoon of poking around, testing stuff, and not knowing alot about php i came up with a solution with help from a friend.
Wp All Import does not allow custom php directly from the field itself, it does however support custom php functions and provides an editor for these on the bottom of the import configuration page. I did the following:
<?php
//Checks Title for keywords and
//uses those to create categories
//We are using our own Main categories so only
//sub and subsub categroies need to be created.
//Call function
[get_subcat_from_title({title[1]},{category[1]})]
//Function
function get_subcat_from_title($title,$defaultcat)
{
if (strpos($title,"Satchel") !== false) {
$cat = "Tassen";
} elseif (strpos($title,"Travel") !== false) {
$cat = "Tassen";
} elseif (strpos($title,"Gusset") !== false) {
$cat = "Tassen";
} else {
$cat = $defaultcat;
}
return $cat;
}
//Checks Title for keywords and uses those to create subcategories
//Call Function
[get_subsubcat_from_title({title[1]},{sub_category[1]})]
//Function
function get_subsubcat_from_title($title,$defaultcat)
{
if (strpos($title,"Satchel") !== false) {
$cat = "Satchel";
} elseif (strpos($title,"Travel") !== false) {
$cat = "Travel";
} elseif (strpos($title,"Gusset") !== false) {
$cat = "Gusset";
} else {
$cat = $defaultcat;
}
return $cat;
}
?>
On the Taxonomies, Tags, Categories option we can create our own hierarchical order like this:
[main category]
+[sub category]
++[sub sub category]
The main category field is given a name we use as our main category.
The sub category is filled with function SUBCAT
The subsub category is filled with function SUBSUBCAT
this way it will create a parent by our own name, a child that has the named 'Tassen' if any keyword is present, and a grandchild with the specific keyword as it's name.
This way i can expand the function using all kinds of statements when the right category isn't present in de provided feed.
thanks #sebastianForsberg for responding.
I hope this helps anyone who comes across a similar problem in the future..

Using three elements condition in PHP

I have a weird bug.
I have A class names Lessons with 3 elements: video, audio & written.
A functios called IsReadOnly supposed to check if a lesson has something only in the 'written' cell while the 'audio' and the 'video' are empty.
This is how it looks:
public function IsReadOnly() {
if ($this->Audio=="" && $this->Video=="" && $this->WrittenLesson!="")
return true;
else
return false;
}
In the PHP page I'm calling the function:
if (!$Less->IsReadOnly()) {
// ...
}
else {
// ...
}
as far as i get - while video/audio will return false, the full condition will return false also and the IF (not the ELSE) will be executed.
But, thats not working. If the video is empty and the audio isn't - everythig is fine. but if the audio is empty and the video isn't - the ELSE is executed. (I've tried replacing between them, nothing...).
What am I doing wrong?
Thanks.
Perhaps you need to make the if more forgiving:
if ($this->WrittenLesson && !$this->Audio && !$this->Video)
Apparently the solution was to make the SSCCE...
While testing I've found the problem. The video wasn't the only cell I had to check because in the database there were two fields that represent video.
Thanks!

Gravity Forms - Get Current Page Number

I have a multi-page form.
I would like to execute some custom JavaScript on the last page of this form. Theoretically, all I have to do is retrieve the current page number and write a conditional.
Simple, right? Apparently not.
My original workaround was like this:
if ($('gform_page').last().css('display') !== 'none') {
// perform custom scripts now that the last
// Gravity Form page is being shown
}
but $('...').css('display') returns undefined on every element I've tried this on within the form. Custom scripts were being fired every time the user hit the "Next" button. No cigar.
Then, after reviewing the Gravity Forms documentation, I found two useful-looking events: gform_post_render and gform_page_loaded.
However, the documentation gives no instruction on how to access the parameters.
jQuery(document).bind('gform_page_loaded', function(event, form_id, current_page){
console.log(current_page);
// returns nothing when loaded in the footer
// returns [Object, object] when placed in an HTML field in the form
});
In addition to not having the correct code, I also suspect I don't have the code in the correct place as I have also fruitlessly tried the following in functions.php and in header.php (as the documentation suggests):
<?php
function enqueue_custom_script($form, $is_ajax){
if ($is_ajax) :
echo '<script>console.log(current_page);</script>';
endif;
}
add_action("gform_enqueue_scripts", "enqueue_custom_script", 10, 2);
?>
Question:
What code do I need to retrieve the current page number, and more importantly, where do I place that code?
I got it.
The function rgpost is, apparently, crucial in accessing the current page number. After some muddling around on my own, I was able to get the following code working in both functions.php and just before the wp_head() function in header.php.
function run_script_on_last_page($form) {
if (!is_admin()) {
$current_page = rgpost('gform_source_page_number_' . $form['id']) ? rgpost('gform_source_page_number_' . $form['id']) : 1;
if ($current_page == 10) {
wp_enqueue_script('custom_script', get_template_directory_uri() . '/js/custom_script.js', array('jquery'), null, true);
}
}
}
add_action('gform_enqueue_scripts_63', 'run_script_on_last_page');
If you're copy/pasting the code above, make sure to:
replace 10 with the page you want to check
ensure your parameters are correct in wp_enqueue_script
replace 63 with your form ID
Some resources I found useful:
this section of the documentation for the gform_validation filter
the documentation for gform_enqueue_scripts.
The OPs accepted answer might well work but it doesn't work if you have the form setup to paginate using Ajax.
In that case I could only get it working using Javascript and the following method;
http://www.gravityhelp.com/documentation/page/Gform_post_render
jQuery(document).bind('gform_post_render', function (event, formId, current_page) {
if (current_page == 2) {
// do something
}
});
You could of course use the formId parameter to limit this to a specific form
The currently accepted answer only works if the user never goes to a previous page in the form, if they do, then gform_sourge_page_number always lags by one. I found a better solution (using this hook for an example, but you should be able to use it within any hook that has the $form passed to it):
function run_script_on_last_page( $form) {
if ( !is_admin() ) {
if ( \GFFormDisplay::get_current_page( $form['id'] ) == 10) {
wp_enqueue_script( 'custom_script', get_template_directory_uri() . '/js/custom_script.js', array( 'jquery' ), null, true );
}
}
}
add_action( 'gform_enqueue_scripts_63', 'run_script_on_last_page' );
GFFormDisplay::get_current_page( $form_id ) is one of many handy undocumented functions.
I wrote a little function that returns the current page:
// Get Gravity Forms Current Page
// Syntax: gf_current_page()
function gf_get_current_page()
{
return rgpost('gform_source_page_number_' . $_POST['gform_submit']) ? rgpost('gform_target_page_number_' . $_POST['gform_submit']) : 1;
}
Further to the accepted answer, here is an example of finding the current page, and dynamically finding how many pages are in the form. This example changes button text based on whether it is the last page of the form, instead of enqueueing a script.
// Change the text of the 'Next' form button to 'Submit' when
// the current page is the final page of the form
add_filter( 'gform_next_button', 'next_to_submit', 10, 2 );
function next_to_submit( $next_button, $form ) {
$replacement_next_button = $next_button;
$last_page_number = 1;
foreach ($form['fields'] as $field) {
$is_hidden = RGFormsModel::is_field_hidden( $form, $field, array() );
if ($field['pageNumber'] > $last_page_number && !$is_hidden) {
$last_page_number = $field['pageNumber'];
}
}
$current_page_number = rgpost('gform_source_page_number_' . $form['id']) ? rgpost('gform_source_page_number_' . $form['id']) : 1;
if ($last_page_number === $current_page_number) {
// If the current page is the final page
$replacement_next_button = str_replace( 'Next', 'Submit', $next_button );
}
return $replacement_next_button;
}
Following code works for me in JavaScript:
$('.gf_step_active .gf_step_number').html()
It will give you the page number of the current page in multi-page form.
Using Jquery
var current_page_ = 1+parseInt(jQuery('.gform_page:visible').index());
Try using this one:
var current_visible_page = jQuery('.gf_step_active .gf_step_number').html();
console.log(current_visible_page);
Use the above method in the console to check how it's working.

Codeigniter--add “active” css class, how to apply on a link?

i have a url like this
http://localhost/bestbookfinder.com/viewallbooks/books/pgn/grid/6
where:
bestbookfinder.com: Project name
viewallbooks : class name
books :function
pgn :Constant Parameter
grid :view type
6 :pagination current page number
so now i am trying to read the above shown url and to apply the CSS class with the following code, but unfortunately my code is not working.
I think i am making mistake when i tried to read the url.
Please help me to solve this problem
<?php
if ( $this->uri->uri_string() == '/books/pgn/grid' )//i think mistake is here
{
echo "".anchor(base_url().'viewallbooks/books/pgn/grid/'.$this->uri->segment(5),' Grid', array('id' => 'gridactive'))."";
}
?>
From the codeigniter manual - uri_string() returns a string with the complete URI. So in your example that would be "viewallbooks/books/pgn/grid/6".
Therefore "viewallbooks/books/pgn/grid/6" != '/books/pgn/grid'
Just do something like this:
if ($this->uri->segment(4) == "grid")
{
// do something
}
if($this->uri->segment(4) == 'grid'){
//carry on

Codeigniter if controller

First of all sorry if its a noob question.
But is it posibble to do this in codeingiter, like if i have a sidebar but i only want to load it in 2 pages
if(controller == 'blog') {
//load sidebar
}
just like in wordpress if is_page
Use $this->router->fetch_class()
if($this->router->fetch_class() == 'blog') {
//load sidebar
}
Also $this->uri->segment(2) will work in most cases, but in some cases like mod_rewrite or when using subfolder or route it may fail.
More simply you can do like this.
$controller_name = $this->CI->router->fetch_class();
if($controller_name === "your_controller_name")
{
//your logic
}

Categories