Wordpress posts in columns - php

I am trying to create a wordpress theme. i would like to have three columns with post excerpts. But the problem is that they don't always have the same height (and i don't want them to), so when in one row a post is too high, the next row will start too far away.
Hmmm, i can really explain it, so i created this fiddle to show what i mean:
//in the fiddle there is html and css making a clear example of what i mean
http://jsfiddle.net/59qyD/1/
As you can see post id#5 is too long, so post #7 doesn't go any more under post #4.
What i would like is to find a solution where the post always "go up" to the previous post in that column. If possible, without any plugins...
Any ideas?

To create a dynamic column height no matter if it's images/posts/products, you can apply Masonry JS
This JS offers you the possibility to fit each new div under the previous div from the above line, and has a great effect of showing it.

Here is a PHP + CSS based solution:
PHP:
$count = 0;
$count_total = 10; // or use dynamic count: count($all_posts)
$columns = 3;
foreach ( $all_posts as $k=>$v ) {
$count++;
$is_first_column = false; // always set to false, then set to true only when the condition matches!
// Now check is this a post for the first column
if( $count==1 || ($count-1)%$columns==0 ) { // check if it's 1st and every 4,7,10 post and place it in 'column 1'
// set additional class for every post that need to be placed in the first column
$is_first_column = true;
}
// Now you can add the additional class to the html markup:
<article id="post-<?php the_ID(); ?>" class="post col<?php if( !empty( $is_first_column ) ) { echo ' column_1'; } ?>">
}
And then use CSS to clear the float for every .column_1.
CSS:
.column_1 {
clear: both;
}
I used similar approach in multiple projects and it worked. The code above may need to me modified a bit to work for your specific theme, but I hope you'll get the main idea.
It will work immediately after page + CSS load (no waiting for JS to load)! :-)

Related

How to create a ecommerce filter with php using the GET method

I know there are better ways to do it, but I really need to create a multiple parameter filter with PHP only in order to filter items by from a json.
The categories are separated by Gender, type of Item, colors etc... I want to be able to select multiple categories, and if only gender is set to show all products, call them using the $_GET method and be able to filter using IFs.
The problem is that my amateur coding skills are not helping much, and I am also not sure if without AJAX there is a better way to do this.
This is what part of my filter looks like:
<ul class="category-menu" name="categoria">
<li><a href="page.php?genid=<?php echo $genid;?>&cat=remeras&col=<?php echo ($_GET["col"]);?>&mar=<?php echo ($_GET["mar"]);?>" name="campera" >Remeras</a></li>
<li>Camperas</li>
<li>Pantalones</li>
<li>Shorts</li>
<li>Vestidos</li>
</ul>
And I have my ifs looking like this:
<?php
}elseif ( !empty($_GET["genid"]) && !empty($_GET["cat"]) && $datosArray[$i]["sex_id"] == $_GET["genid"] && $datosArray[$i]["categoria"] == $_GET["cat"]){
?>
<!-- Individual Product full Code -->
...
<!-- /Individual Product full Code -->
<?php
}elseif (!empty($_GET["genid"]) && $datosArray[$i]["sex_id"] == $_GET["genid"]){
?>
<!-- Individual Product full Code -->
...
<!-- /Individual Product full Code -->
<?php
}} ?>
Right now the only "filter" it recognizes is the Gender one and its displaying all products even if the $_GET is set and displayed properly.
Thank you all in advance.
If I turn your code into psuedo-code, it reads like this.
if we have the following: a genid, cat
and the genid is the same as $datosArray[$i]["sex_id"]
and the datosArray[$i]["categoria"] is the same as $_GET["cat"]
then display the product
Otherwise, if we have a genid
and that genid is the same as $datosArray[$i]["sex_id"]
then display the product
If that is what you where intending to have happen, then you might want to var_dump or print_r all of your variables, and make sure nothing unexpected is happening.
You talked about wanting to use multiple categories. There are two ways of doing this that I can think of right now. The first is to have a comma separated list of categories href="...cat=pantelones,vestidos,shorts, and then turn that into an array $cats = explode(',', $_GET['cat']). You would then check for a specific category with in_array('pantelones', $cats).
The second is to create an HTML form that uses a checkbox to select multiple categories, and then if you simply add brackets to the end of the checkbox's name, then when the user submits the form, PHP will automatically convert $_GET['cat'] into an array for you See this SO question for more info about what I mean.
I would do things more like this.
function display_product($productData){
/* Add code here to display your product */
}
foreach($datosArray as $productData){
/* Always display the product if the gender ID was not set */
if ( empty($productData['genid']) ){
display_product($productData);
}
/* Otherwise only display the product if it matches what is in $_GET[] */
if (
isset($_GET["genid"]) && $_GET["genid"] == $productData['sex_id']
&& isset($_GET["cat"]) && $_GET["cat"] == $productData['categoria']
&& isset($_GET["mar"]) && $_GET["mar"] == $productData['Marca']
){
display_product($productData);
}
}
I know you already said you knew that there where better ways of filtering data, I just want to add that once it comes time to add/edit/delete data, databases become super useful. They are also speedier at filtering out the data you want.
You introduced an XSS vulnerability. You should always escape your variables before outputting them, like so. (I like to use <?= which is just a shorthand for <?php echo.)
<ul class="category-menu" name="categoria">
<li><a href="page.php?genid=<?= (int)$genid ?>&cat=remeras&col=<?= htmlspecialchars($_GET["col"]) ?>&mar=<?= htmlspecialchars($_GET["mar"]) ?>" name="campera" >Remeras</a></li>
<li>Camperas</li>
<li>Pantalones</li>
<li>Shorts</li>
<li>Vestidos</li>
</ul>
PHP offers a http_build_query($arrayOrObject) function which is useful on its own. Check the docs.
I made myself a tiny wrapper for the function that I normally use for such things.
/**
* Build query parameters string from given arrays ($_GET by default)
* #param array $newGet
* #param null|array $currentGet
* #return string
*/
function new_build_query(array $newGet = [], ?array $currentGet = null)
{
if (!isset($currentGet))
$currentGet = $_GET;
$newGet = array_merge($currentGet, $newGet);
ksort($newGet);
return http_build_query($newGet);
}
Given the current URL being https://example.com/?page=2his can be used like this:
$params = new_build_query([
'sort' => 'asc',
'filter' => 'female',
]);
// $params === 'filter=female&page=2&sort=asc'
$redirectUrl = "https://example.com/?{$params}";
your code is a bit confusing in the way it is displaying the results. So I mean you want to filter a product, from there the genre and following specific details such as color, size etc. on request by ajax is possible yes. but I advise to leave these parameters in database and from this make the filters. If you are based only on json use json_decode ($ data, true) to make it an array so you can do the filters more simply. I also advise using a template engine (twig for example) to separate php code from html. that would be better for you

Joomla custom fields inside template

I would like to customize my template for Joomla 3.7 so that I can use the new feature of Joomla 3.7, Custom fields (com_fields), and display and format them via CSS in my template where I need to display them.
Can someone suggest me the PHP code I should use in the template to display field(s), some example please.
Thanks in advance.
For everyone getting late to the party. In case you want to use your custom form fields in a Module-Override (which really are the only way to modify j!-templates, so google 'joomla template override') you can use this handy snippet:
<?php
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
$jcFields = FieldsHelper::getFields('com_content.article', $item, true);
$itemCustomFields = array();
foreach($jcFields as $field) {
$itemCustomFields[$field->name] = $field->rawvalue;
}
?>
Now you cna use your customfields like so: itemCustomFields['customFieldName1']
Haven't tested in article overrides. May soon, if so, this will get updated.
certainly not the right way to do it but I had the same need and I found a work around based on https://www.giudansky.com/news/12-coding/146-joomla-custom-fields
Copie default.php from /components/com_content/views/article/tmpl/default.php to
templates/YOUR_THEME/html/com_content/article/default.php
Add following code line 25 :
$myCustomFields = array();
foreach($this->item->jcfields as $field) {
$myCustomFields[$field->name] = $field->value;
}
$GLOBALS['myCustomFields'] = $myCustomFields;
Typically you put on a global var the content of fields attached to your article.
On your template page you can know retrieved value of your field.
just print_r($GLOBALS['myCustomFields']); to view the content of your array.
That will do the trick waiting for a better answer..
This is absolutely the wrong way to do this I think but I was tearing my hair out so i came up with this quick db query to return custom field values in the template. surely this violates some kind of joomla protocol?
obviously this assumes you can get $articleid into your template already which is the Current ID of your article.
I too am waiting on a better solution but hope this helps
$db =& JFactory::getDBO();
$sql = "select * from #__fields_values where `item_id` = $articleid";
$db->setQuery($sql);
$fieldslist = $db->loadObjectList();
echo $fieldslist[0]->value;
echo $fieldslist[1]->value;
echo $fieldslist[your field ID here]->value;
I found it was easiest to follow how com_fields does it in its rendering code. In Joomla!3.7+, you'll find it in [joomla_root]/components/com_fields/layouts/fields/render.php .
Here are the main parts you need to reproduce the formatting that Joomla has:
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
<dl class="fields-container">
<?php foreach ($this->item->jcfields as $field) : ?>
<?php // If the value is empty do nothing ?>
<?php if (!isset($field->value) || $field->value == '') : ?>
<?php continue; ?>
<?php endif; ?>
<?php $class = $field->params->get('render_class'); ?>
<dd class="field-entry <?php echo $class; ?>">
<?php echo FieldsHelper::render($context, 'field.render', array('field' => $field)); ?>
</dd>
<?php endforeach; ?>
</dl>
This loops through all available tags for the component or article. The nice thing about this method is it still applies the render classes you include with the fields.
Make sure to set Automatic Display to Do not automatically display on your fields; otherwise you will see them twice on your page view.
If you want to just target specific fields to show, you can use the name of the field to target it. (The label and value pair is underneath.) See the field Joomla docs for more info.
I implemented this small function to get specific custom field values:
function getCustomFieldValue($field_name, $article_id, $default_value = '') {
// Load custom field list
$fields = FieldsHelper::getFields('com_content.article', $article_id, true);
$field_ids = array_column($fields, 'id', 'name');
$model = JModelLegacy::getInstance('Field', 'FieldsModel', array('ignore_request' => true));
// Return the value if the field exists, otherwise the default
return array_key_exists($field_name, $field_ids)
? $model->getFieldValue($field_ids[$field_name] , $article_id)
: $default_value;
}
Usage:
$some_field_value = getCustomFieldValue('some-field-name', $some_article_id);
Optimization: I placed the function into a helper class, implemented the variables $fields, $field_ids and $model static and checked if they are already loaded to prevent redundant loading of the same data.

Drupal 8 change image style in first row on views list

I have created view that displays on page 10 newest article. I have in row two fields: image and content. In settings of image field I chose image style (for example: medium). How can I change image style to another (example: large) only in first row?
I have tried it in preprocess but i don't know where is stored information about image style:
function theme_preprocess_views_view_unformatted__lista_depesz_default(&$variables) {
$view = $variables['view'];
$rows = $variables['rows'];
$style = $view->style_plugin;
$options = $style->options;
$variables['default_row_class'] = !empty($options['default_row_class']);
foreach ($rows as $id => $row) { $variables['rows'][$id] = array();
$variables['rows'][$id]['content'] = $row;
$variables['rows'][$id]['attributes'] = new Attribute();
if ($row_class = $view->style_plugin->getRowClass($id)) {
$variables['rows'][$id]['attributes']->addClass($row_class);
}
if ($id == 0 && $row['content']['#row']->_entity->field_image[0] != NULL) {
//some php code to change image style
}
}
}
Regards
You can create view with original images, and set style inside your twig files, using for example twig tweak:
https://www.drupal.org/project/twig_tweak
Inside twig file you can set any style with conditioning
{{ 'public://images/ocean.jpg' | image_style('thumbnail') }}
Regarding your code and your explanations, I'm not sure to understand what you are trying to achieve.
1/ you try to add a CSS class to the 1st image of your view. Why not using the following CSS path .my_view .first img {}
2/ if you try to call another image style, can you create a view with only the 1st item, or a promoted? Then a second view with the rest of the items ?
3/ if you try to call another image style, you can do it without any code.
You install the module http://drupal.org/project/views_conditional then you add 2 images with 2 different image style, and you apply your condition inside the condition fieldset.
I really prefer the solution 3 because it's pure Drupal build.
I hope it helps.
Cheers

how to write a script output in a post in the act of creation of these posts?

Hello community WordPress forum.
I have a need to write the posts the output of a function, but all to getting to do is to display real-time and run this script / function in all posts, with I do to write the posts the output of a function instead of display it in posts?
because what 's happening is that the script is running on all posts, and each refresh / access the pages, a new script number is generated! I would like the generator create a different number for each post, but write to output them, and not display a number to each new access.
// Declare the function
function gen_num()
{
// DETERMINE THE CHARACTER THAT CONTAIN THE PASSWORD
$caracteres = "012345678910111213141516171819";
// Shuffles THE CHARACTER AND HANDLE ONLY THE FIRST 10
$mistura = substr(str_shuffle($caracteres),0,10);
// DISPLAYS THE OUTCOME
print $mistura;
}
// Add custom post content, inject function in content.
function add_post_content($content) {
gen_num();
return $content;
}
add_filter('the_content', 'add_post_content');
see in herculestest.tk, browse the pages, make f5 to refresh.
Thank you very much.
==========================================
another attempt:
I created a custom field from ACF plugin named: numeration:
function gen_num()
{
global $post;
$mistura = get_post_meta( $post->ID, 'numeration', true );
if ( '' == $mistura ) {
//DETERMINE THE CHARACTER THAT CONTAIN THE PASSWORD
$caracteres = "012345678910111213141516171819";
// Shuffles THE CHARACTER AND HANDLE ONLY THE FIRST 10
$mistura = substr(str_shuffle($caracteres),0,10);
update_post_meta( $post->ID, 'numeration', $mistura );
}
//DISPLAYS THE OUTCOME
print $mistura;
}
// Add custom post content, inject function in content.
function add_post_content($content) {
gen_num();
return $content;
}
add_filter('the_content', 'add_post_content');
this solution to not change the number each new access, now writing these data permanently in the database ?? because're not recording! if I change my theme, all the numbers in all the posts disappear, and if I make any errors in functions, php, these add up numbers, because they depend on the function running at him display the values, and worst of all, to fix the functions.php, the script will return to run and therefore, will be a re-run, which means that it will generate new numbers on all posts !! and this can not happen, should I ever have the same values!
The Post ID is unique in WordPress, is that number adequate for your needs?
Otherwise you'd need to generate a unique ID when the post is published and save it in a custom field. (Instead of your gener_numb function look into uniqid: http://php.net/manual/en/function.uniqid.php.)

How to create a hyperlink to a file in an array (paginated files)

I've been playing around with pagination using arrays in php.
I have an array of posts that I use to break the content of a page up into smaller chunks. It works and returns the content as I would like.
<?php
// let's paginate data from an array...
$posts = array(
// array of posts
"blog/posts/06-19-tues.php",
"blog/posts/06-16-sat.php",
"blog/posts/05-26-sat.php",
"blog/posts/05-23-wed.php",
"blog/posts/05-09-wed.php"
);
// how many records should be displayed on a page?
$records_per_page = 3;
// include the pagination class
require 'zebra/Zebra_Pagination.php';
// instantiate the pagination object
$pagination = new Zebra_Pagination();
// the number of total records is the number of records in the array
$pagination->records(count($posts));
// records per page
$pagination->records_per_page($records_per_page);
// here's the magick: we need to display *only* the records for the current page
$posts = array_slice(
$posts,
(($pagination->get_page() - 1) * $records_per_page),
$records_per_page
);
?>
<?php foreach ($posts as $index => $post):?>
<?php include $post; ?>
<?php endforeach?>
<?php
// render the pagination links
$pagination->render();
?>
My question is now how to link to the individual posts from elsewhere on the site. Since they will, ultimately move from page to page, linking directly to the static file won't work. At first, I had given each post a unique id and used that to link to the post but that won't work now since the link will change, dynamically.
I've looked at array_search() and it looks promising but I don't understand it's use enough to get it to produce a hyperlink.
I'm not sure I've phrased this question all that well. apologies if I don't make much sense.
If I understand you correctly, I think something like this will work:
if (isset($_REQUEST['page']) {
$found = array_search($_REQUEST['page'], $posts);
if ($found) {
$pagination->set_page(floor($found/$records_per_page)+1);
}
}
Then you can use a link like
$link = 'whatever';

Categories