Quantcast
Channel: WordPress › Support » Forum: Hacks - Recent Topics
Viewing all 8245 articles
Browse latest View live

nicholasgalgay on "Setting last login in users chosen timzone."

0
0

Hello,

I have my site set up so it captures the users Timezone when they update their profile, and it's then stored in my database as "America/Toronto" for example. The problem I am having is, I am trying to capture the login time of the user and store it as their local time. I've been reading on this for a few days but can't figure it out. In my functions file I have

add_action('wp_login','last_login', 10, 2);
    function last_login($user_login, $user) {
    global $wpdb;
    global $current_user;
    $user = $user->ID;
    $timezone = ThemexUser::$data['user']['profile']['timezone'];
    date_default_timezone_set($timezone);
    $wpdb->query("SET time_zone = '".date('P')."'");
    $wpdb->query( "UPDATE $wpdb->users SET last_login = CURRENT_TIMESTAMP() WHERE ID = '$user'" );
}

and it's saving the time as wordpress' set time. Any help is greatly appreciated.


jonytje on "Nested loop get_posts("

0
0

Hi,

I need to fix a nested loop: first of all i'm getting all posts and in the loop of posts i'm getting al attachments (images) twice but in a different order.

The problem is it only works on the first item and not on the second. How do i fixed this properly?

<div class="content">
    <?php
    $args = array('posts_per_page' => 5, 'offset' => 0);
    $projectCount = 0;
    $myposts = get_posts($args);
    foreach ($myposts as $post) : setup_postdata($post);
    $projectCount++;
        ?>
        <section class="project" id="<?php echo $projectCount ?>">
            <h2><?php the_title(); ?></h2><p><strong><?php echo wp_strip_all_tags(preg_replace('/<img[^>]+./', '', $post->post_content)); ?></strong></p>
            <div class="colHolder">
            <?php
            $media = get_posts(array(
                'post_parent' => $post->ID,
                'post_type' => 'attachment',
                'post_mime_type' => 'image',
                'orderby' => 'title',
                'order' => 'ASC'
            ));
            //print_r($media);
            ?>
            <?php foreach($media as $key => $image): ?>
                <?php if(!empty($image->post_title)): ?>
                <div class="col<?php if(!empty($image->post_content)){echo $image->post_content;}else{echo 1;} ?> colImg">
                    <div class="img imgGrid" data-order="<?php echo $image->post_excerpt; ?>" style="background: url(<?php echo $image->guid ?>) 50% 50% no-repeat;">
                        <img src="<?php echo $image->guid ?>" alt="" />
                    </div>
                </div>
                <?php endif; ?>
            <?php endforeach; ?>

            <ul class="hiddenGal">
            <?php
                $allmedia = get_posts(array(
                    'post_parent' => $post->ID,
                    'post_type' => 'attachment',
                    'post_mime_type' => 'image',
                    'orderby' => 'caption',
                    'order' => 'ASC'
                ));
                //
                foreach($allmedia as $key => $imagel):
            ?>
                <li data-img="<?php echo $imagel->guid ?>" class="hiddenImage"></li>
            <?php endforeach; ?>
            </ul>
            </div>
        </section>

<?php
endforeach;
wp_reset_postdata();
?>

</div>

oeysteinlo on "Wordpress with Sensei plugin. Trigger action on page load"

0
0

I am trying to set up a some fairly basic functionality on a wordpress website through a plugin. The website is academic, and is using the Sensei-plugin from WooThemes to set up a framework for creating and taking courses.

I want to trigger an action to store some data when the user views a lesson for the very first time. Sensei will already store some data when a lesson is finished, and that is triggered by the user pressing a button.

My question is this: How do I trigger an action when a lesson is loaded? Each lesson is stored as a post with a custom post_type.

I am, as stated previously, aware that this is probably a very basic question. I am working to figure it out on my own as well.

bugnumber9 on "Generate custom taxonomy term slug - how?"

0
0

I have a CPT "Listings" and a custom taxonomy "Locations" for it.
Locations are US states and cities, and states are unique while cities aren't.

Now I'm adding 2 states: Ohio and Nevada, each of them has Cleveland city. So the 1st Cleveland slug looks like /cleveland/ and the 2nd becomes /cleveland-nevada/
I want these slugs to be consistent, so I manually edit them to be /cleveland-oh/ and /cleveland-nv/ afterwards.

Can I achieve this automatically on term creation?
I figured out how to add custom fields to terms, so I can add oh and nv as custom field values to states.
But... What now? :) How do I force term slugs to be generated using name+custom field value?

nabtron on "Comments or child posts for question answers?"

0
0

I wanted to know the best way to make a question answer system?

Will it be better to use comments as "Replies" or the "child posts" and why?

Thanks.

dalemoore on "How to view posts from a specific year through URL (?year=2016)?"

0
0

I'm still learning PHP, so I apologize if this is a dumb question.

I've been trying to figure out how to make a form that will allow to view posts only from a specific year. I know that WP_Query has the ability to do this using "year", but how do you do it through a URL? For instance, like going to http://site.com/custom-post-type/?orderby=date&order=DESC&year=2015 would show all posts from 2015, in descending order by date. Is this not how it should work?
So, I want a select dropdown that gets populated with all of the posts from a specific custom post type's years. There are currently only posts from 2015 and 2016 in this CPT, so 2015 and 2016 should be in the dropdown. And when you click 2016, and submit, it should then display only the CPT posts from 2016.

$args = array(
    				'post_type' => array('plant'), // display only Plants; otherwise, every post type is shown
    				'orderby' => $order_by, // this comes from a select, options of date, title, menu_order, and random currently
    				'order' => $order, // this comes from a select, ASC and DESC are the options
    				'posts_per_page' => $posts_per_page,
    				'paged' => $paged,
    				'year' => $year, // here lies the issue. If I hard code in 2015 here, it works on the page itself but not through the URL. How to pass into this through the URL?
  				);

  				// The Loop
  				$loop = new WP_Query( $args );
    			if ( $loop->have_posts() ) : ?>

The form (currently broken for the year):

<form action="" method="get">
            	<div class='post-filters'>
              	Sort by:
              	<select name="orderby">
                	<?php
                		$orderby_options = array(
                  		'menu_order' => 'Default Sort',
                			'date title' => 'Date', // 'post_date' => 'Order by Date',
                			'title' => 'Title', // 'post_title' => 'Order by Title',
                			'rating' => 'Rating',
                			'company' => 'Company',
                			'rand' => 'Random',
                		);
                		foreach ($orderby_options as $value => $label) {
                			echo "<option ".selected( $_GET['orderby'], $value )." value='$value'>$label</option>";
                		}
                	?>
              	</select>
              	Order:
              	<select name="order">
                	<?php
                  	$order_options = array(
                    	'ASC' => 'Ascending',
                    	'DESC' => 'Descending',
                  	);
                  	foreach ($order_options as $value => $label) {
                    	echo "<option ".selected( $_GET['order'], $value )." value='$value'>$label</option>";
                  	}

                  ?>
              	</select>
              	Year:
              	<select name="year">
                	<option value="any">All</option>
                	<?php
                		global $post;
                                // found this snippet elsewhere to populate the post years... is there a better method?
                		$query = 'post_type=plant&numberposts=-1&orderby=date&order=DESC';
                		$myposts = get_posts($query);

                		foreach($myposts as $post) {
                			$year = get_the_time('Y');
                			$years[] = $year;
                		}

                		$years = array_values( array_unique( $years ) );

                		foreach ( $years as $year => $label) {
                			echo "<option ".selected( $_GET['year'], $year )." value='$year'>$label</option>";
                		}
              		?>
              	</select>
              	<input type="submit" value="Submit" />
              </div>
          	</form>

I'll probably take a break and come back later and it will slap me in the face... but I'm stumped.

jelmer16 on "Change the "add to cart" button text to the price of the product"

0
0

Hi,

I wnat the "add to cart" button text changed in the price of that product.
I've figured out were to change the text, but how do I replace the text with the variable 'price' of that product?

add_filter( 'woocommerce_product_single_add_to_cart_text', 'woo_custom_cart_button_text' );
function woo_custom_cart_button_text() {
         return __( 'My Button Text', 'woocommerce' );
}

Guido on "Adding post_class to the loop"

0
0

Hi,

I have a theme which displays my posts in 2 columns. I clear each left post. I currently use this wrapper around each post:

<div class="post-home<?php if( $wp_query->current_post%2 == 0 ) echo ' left'; ?>">
// post content
</div>

With CSS:

.post-home {width:48%; float:left; margin:0;}
.post-home.left {clear:left; margin:0 4% 0 0;}

But I now want to support the post_class so I can use extra Post Formats such as Aside.

That's why I have to include the post_class to the loop (among other things ). Normally I can use something like this:

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

But because I have to clear each left post I've build this:

<?php if( $wp_query->current_post%2 == 0 ) : ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('post-home left'); ?>>
<?php else : ?>
<article id="post-<?php the_ID(); ?>" <?php post_class('post-home'); ?>>
<?php endif; ?>
// post content
</article>

Does work fine, but I'm wondering if this can be improved/fine-tuned?
And should I use the article tag?

Any thoughts?

Guido


joshlove on "WooCommerce - Slow Order Search"

0
0

Hey everyone,

Looking to improve my search time whenever it comes to WooCommerce->Orders. We have 120,000 orders, and the search time is pretty awful. Here is my base line test (done on localhost):
-Search by order number - 25 seconds
-Search by name - 50 seconds
-Search by Email - 55 seconds

After much searching, I didn't see many viable options (outside of using a third party service). So I decided to make some changes to the queries in the plugin itself (purely for testing). I was able to reduce search times to the following:
-Search by order number - 6 seconds
-Search by name - 9 seconds
-Search by Email - 9 seconds

These are much more acceptable times (can probably get better times with more tweaks), but I had to edit a function in the file: woocommerce->includes->admin->class-wf-admin-post-types.php.

I don't want to edit the plugin file itself, and the function is already declared first by woo commerce, so I can't call it in my functions.php file. How can I get my changes to take effect?

eddr on "Can't save compressed string in options table (set_transient/update_option)"

0
0

Hi

I'm trying to save big string as a transient and I want to compress it. I've tried PHP's gzcompress and gzencode and I can compress and decompress fine.
However, if I try to save the data in the DB using set_transient or update_option, it fails - no data is stored.
tried PHP 5.6 and PHP 7 and I'm using transients otherwise just fine

Any clue?

Thanks

mae48 on "push left not working well"

uthor on "Can't login before/after update of rename-wp-login"

0
0

Hi everyone.

I can't login into my admin account on my site. I'm using plugins like WordFence, Better Security WP and rename-wp-login. I have changed my login method by rename-wp-login on mysite/support2. After last update or before next when i tried to get in my account it appears this: "You must log in to access the admin area". After i add something behind "login" in path: wp-content/plugins/rename-wp-login it happend nothing, and when i tried to login by mysite/wp-login.php it retreats to wp login site again and again. I asked to admin server to delete file called rename-wp-login and still nothing. Excuse me if my english is bad. Please for help what can or should i do and how to log in to my account on my site. To last or before next update i was logging in without any troubles and i didn't change anything.

nabtron on "first hook to use current page post id"

0
0

I'm trying to find the first hook that will pass the current post id, as I would like to update the current post (by getting its id) and the variables submitted to that page.

I hope it makes sense :/

harpocalypse on "Trouble with Plugin to display some info from another db"

0
0

Hi everyone!

I am currently being driven insane by my first plug-in. The only thing I want it to do is display some data hosted in an external db. In order to make it more WP friendly I decided to use the wpdb object ...

This is a reduced version of the code so far:

function wp_add_ads($content) {
global $post;

    if( !is_object($post) ) {
		return $content;
	}

	if ($content != "" && $post->post_type === 'post') {
		$category = get_the_category();
		$adcontent = "<div class=\"adcontainer\">\n";
		$adcontent .= "<div class=\"container\">\n";
		$adcontent .= "--- START ---<br>";
		require_once('conn.php');
		try
		{
			$adcontent .= "--- INSIDE TRY ---<br>";
			$feat = array();
			$shops = array();
			$db = new wpdb($dbuser, $dbpass, $dbname, $dbhost);
            		if(count($feat)<4)
			{
				$rows = $db->get_results("SELECT idshop FROM shops WHERE shopvisible", ARRAY_A);
				foreach($rows as $key=>$shop)
				{
					var_dump($shop);
					$shops[] = $shop["idshop"];
					$adcontent .= "s".$shop["idshop"];
				}
				var_dump($shops);
				$adcontent .= "--- SHOPS: ".implode(',', $shops). "---<br>";
			}
			/* the code goes on and on */

			$adcontent .= "--- END ---<br>";
			$adcontent .= "</div>\n</div>\n";
			$content = $adcontent . $content;
		} catch (Exception $e) {    // Database Error
			echo $e->getMessage();
        	}

}
return $content;
}

add_filter('the_content', 'wp_add_ads', 2000000);

?>

That bit of code should be enough to explain my problem ... What I want to do is get 4 items for sale from another db I own. To do that, I get all the shops, then choose 4 at random, then choose a random article from each one of them. In the code above there is only the code up to getting the name of the shops.

Because that's where the problem starts as far as I can see ... In the var_dumps I get the right information (actual data from the db):

array(1) { ["idshop"]=> string(1) "3" }
array(1) { ["idshop"]=> string(1) "6" }
array(1) { ["idshop"]=> string(1) "7" }
array(1) { ["idshop"]=> string(1) "8" }
array(4) { [0]=> string(1) "3" [1]=> string(1) "6" [2]=> string(1) "7" [3]=> string(1) "8" }

But when $content gets displayed, it shows this:

array(0) {
}
<div class="adcontainer">
<div class="container">
--- START ---
--- INSIDE TRY ---
--- SHOPS: ---
--- END ---
</div>
</div>

I thought that it might be some other filter changing the content, so I changed the priority to 2000000.

Looking at the whole thing, the most reasonable answer is that the db connection is not working, but the var_dumps are showing the correct information, but the information seems to disappear when it comes to the actual content display?

At this point I am ready to blame little grey men, so before I get there, I wanted to check if I had forgotten to do something really obvious in the world of plugins?

Thanks in advance for any help with this!!!

Martin Zunec on "Disable/remove password - login only with username"

0
0

Is this possible? I tried removing password in wp-login.php and some other files but no succes. I want all users to be able to login with their username only, without having to enter their password at all.

Hope someone can help me, thanks!


ajsunnyboy on "Rewrite Isuues in custom taxanomy"

0
0

Problem in hand :

I have custom categories in wordpress named "Product Categories" with custom post type "Products".

i want to change urls from

somesite.com/product/airconditioner/voltas/productname
to

somesite.com/airconditioner/voltas/productname
Code to register post and categories

class aw_products_post_type {

function __construct(){
   $this->aw_register_post_type();
   $this->aw_add_post_type_actions();
   $this->aw_add_post_type_filters();
}

public function aw_register_post_type(){
    // Labels
$labels = array(
 'name' => __('Products','framework'),
'singular_name' => __('Product','framework'),
'add_new' => __('Add new','framework'),
'add_new_item' => __('Add new product','framework'),
'edit_item' => __('Edit','framework'),
'new_item' => __('New product','framework'),
'view_item' => __('View product','framework'),
'search_items' => __('Search product','framework'),
'not_found' =>  __('No product found','framework'),
'not_found_in_trash' => __('No product found in trash','framework'),
'parent_item_colon' => '',
'menu_name' => __('Products','framework')
);

$short_url = (get_option('tz_products_short_url') != '') ?         get_option('tz_products_short_url') : 0;
$slug_first_part = ((get_option('tz_custom_products_slug') != '') ?     get_option('tz_custom_products_slug') : 'product');
if($short_url == 1) {
$slug = $slug_first_part;
} else {
$slug = $slug_first_part."/%product_category%/%product_brand%";
}

// Arguments
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'menu_icon' => get_stylesheet_directory_uri().'/img/admin/admin-    products.png',
'rewrite' => true,
'capability_type' => 'post',
'rewrite' => array("slug" => $slug), // Permalinks format
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'taxonomies' => array('post_tag'),
'supports' => array('title','editor','author','thumbnail','excerpt', 'comments', 'tags')
);

Value of tz_custom_products_slug in wp_option -> Product

Solutions tried in .htaccess

<IfModule mod_rewrite.c>
RewriteEngine on

RewriteBase /
RewriteRule ^product/(.+)$ /$1 [L,R]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.+?)/?$ $1.php [L]
</IfModule>

The above solution didn't worked.

Solution 2 Tried and failed as follows:

changed this from above code $slug = $slug_first_part."/%product_category%/%product_brand%";

to this

$slug = "/%product_category%/%product_brand%";
This caused 2nd custom taxanomy as page not found that is brands that shows urls like this :

sitename.com/brands/acer/
If you need the whole custom taxanomy code for brand and product_category let me know.

To check the original urls check it on : https://www.pricereview.in/product/digital-cameras/olympus/olympus-sz-17-digital-camera/

Similarly my custom taxanomy contains basename categories. i also want to remove it.

This is how urls are working. i want to convert this

https://www.pricereview.in/categories/mobile-price-in-india/

to

https://www.pricereview.in/mobile-price-in-india/

djsheld on "Add static section to dynamic homepage"

0
0

Hello, I am running a theme called vertex by elegant themes. I am having an issue. My boss likes the setup of the dynamic homepage that displays sections as follows: Projects, Post slider, testimonials, meet the team. But he wants a couple paragraphs to display just before the dynamic list. How do i go about adding a custom static section to the dynamic homepage?

poopymonster on "Append to outgoing links"

0
0

Hello,
I have several hundreds of images in posts hosted by Imgur. The links to the images look like this:
"http://imgur.com/F0ofgw8"
or
"http://imgur.com/F0ofgw8.jpg"

What I need is to have all the images automatically link to this instead:
"http://imgur.com/memegen/create/F0ofgw8"

(the F0ofgw8 part is different for each image)

Currently I use the Imgur oEmbeds plugin for displaying the images.

How could I accomplish this, preferably without using shortcodes for each image or do manual search and replace queries after new images are added?

Thanks in advance!

morollian on "Notification to the author when certain category is added to his/her post"

0
0

Hello,

I'm trying to make wordpress send an email to the autor of a post when certain category is added. The posts are submited from the front-end, so it make sense to tell the autor when I make some change...

So far I managed to send emails when the post is published, using the following code:

function post_published_notification( $ID, $post ) {
    $author = $post->post_author; /* Post author ID. */
    $name = get_the_author_meta( 'display_name', $author ); // I get the name of the author
    $email = get_the_author_meta( 'user_email', $author );// I get his email
    $title = $post->post_title;
    $permalink = get_permalink( $ID );
    $edit = get_edit_post_link( $ID, '' );
    $to[] = sprintf( '%s <%s>', $name, $email );
    $subject = sprintf( 'Published: %s', $title );
    $message = sprintf ('Thanks a lot, %s! We gave the title “%s” to your post.' . "\n\n", $name, $title );
    $message .= sprintf( 'View: %s', $permalink );
    $headers[] = '';
    wp_mail( $to, $subject, $message, $headers );
}
add_action( 'publish_CustomPostType', 'post_published_notification', 10, 2 ); // Where CustomPostType is the slug of my custom post type

I've been browsing through the codex, but i can't find any hook to a category change.

Some guidance would be really apreciated!
Thanks a lot!

amandathewebdev on "JavaScript/jQuery toggle not working"

0
0

Hi all,

I'm hoping someone can give me advice on this. I have a JavaScript function that used to work, and now it doesn't. On this page: http://www.nfe-lifts.com/inventory/ when you check "Advanced Search", a hidden div is supposed to show.

Here is the function:

$('#advanced-options').on('change', function() {

   $.cookie('advanced-search', $(this).is(':checked')?'1':'0');

   if($(this).is(':checked')) {
       $('#advanced-div').show();
   } else {

       $('#advanced-div').hide('slow');

   }

   if($.cookie('advanced-search') == '1') {

        $('#advanced-options').prop('checked', true).trigger('change');

   }
 });

I'm on WP Engine and recently learned that they block certain cookies. They assured me that's not what's happening here. I'm not sure why this isn't working. Any help would be appreciated.

Viewing all 8245 articles
Browse latest View live




Latest Images