INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How can I get a comment ID on Submit? I've added an attachment field to my comment form. It stores the files on Amazon AWS and writes the URL, user ID, post ID, and a few other things to a custom table. I'm having some difficulty getting the comment ID in order to properly associate the attachment with the comment. Is there a good way to get the comment ID as it is being written? I've looked over the documentation and cant seem to find anything that would get my comment ID on submit.
You can hook `comment_post` and add your logic with the comment id // Save the data along with comment id add_action( 'comment_post', 'wti_save_comment_data' ); function wti_save_comment_data( $comment_id ) { // Use the comment id and add your logic }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, comments, attachments" }
woocommerce stored variable In wordpress, all information can be retrieved via `$post` or `wp_query`, in woocommerce, is there something similar? I want to display information of each product, on a page next to the picture. I have two questions. 1. How can i get to know, which variable does woocommerce uses to store the data. 2. In General, if we want to know the meta of any post,page, how can we pull it aganist each id, where id is generic (we don't know, its dynamic like `$post->ID`)
There is `$woocommerce`, which is is crucial. Several classes stored into this, see woocommerce class reference and additionally WC API Docs. If you're looking for product information: $product = get_product( $post->ID ); is certainly a good entry point. If you're already on a product page or generally in the wc loop, you often have `$product` already available. Another thing to add is, wc product(s) are are just a custom post type, so you can do a lot by using wordpress core functions - like: $all_meta = get_post_meta( get_the_ID() ); echo $all_meta; But for some things you need or at least it's easier to use wc functions, to know these you have to read the plugins documentation, e.g. useful functions. Same applies to action and filter hooks. Generally, take a closer look at the linked - and the not linked - information, the source and the variables/objects themselves to get deeper into that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "loop, plugins" }
Check if custom thumnail size image has been cropped to the correct dimensions I'm looking for a way to check if an image has properly created a custom thumbnail size that has been hard cropped. add_image_size( 'homepage-thumb', 1676, 828, true ); $size = "homepage-thumb"; echo wp_get_attachment_image( $attachment_id, $size ); This works well if the uploaded image is large enough but if it's smaller than the dimensions defined in add_image_size the aspect will be out which invariably breaks a layout. Is there a way to check the thumbnail before echoing the image?
$image_attributes = wp_get_attachment_image_src( $attachment_id, $size ); Returns an array containing: [0] => url [1] => width [2] => height [3] => boolean: true if $url is a re-sized image, false if it is the original. Even though you pass the $size as parameter, while returning; it returns the actual width and height of the image irrespective of the image being cropped or not. Then you can check for the width and height if these are smaller then the requirement. OR better apply min-width, min-height in CSS or jQuery.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "thumbnails, images" }
How we add tabs in plugin page I want to add tabs in my test-plugin. I have add a folder '3 test plugin' with file '3 test-plugin.php'. I have activate plugin and add in the setting admin menu. Please give the details of adding tabs in my plugin file. thanks in advance. file code is follow: ## Hello World Options Enter Text " /> (ex. Hello World) " />
If you are looking to add tabs in admin page then you can try doing this: <h3 class="nav-tab-wrapper"> <a class="nav-tab nav-tab-active" href="#">Test1</a> <a class="nav-tab" href="#">Test2</a> <a class="nav-tab" href="#">Test3</a> <a class="nav-tab" href="#">Test4</a> <a class="nav-tab" href="#">Test5</a> <a class="nav-tab" href="#">Test6</a> </h3> this will give you native look and feel
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, tabs" }
Posts and Pages not showing on admin, but showing in theme I've just transferred a WordPress install over from and old IIS server set up by our client, to our new Lunix based VPS. Whether that is relevant or not, i'm not sure. I've changed all the usual settings and database options i'd usual do on moving a website to a new/live server environment.. This has worked perfectly other than the data doesn't show in the WordPress admin specifically, but does if you visit www.lenstec.co.uk. That suggest the data is being successfully pulled in as it normally would. My initial thoughts are that this may be a global variable somewhere within the theme that WordPress does not like? Unfortunately, i've check through my function file and corresponding theme files and not come across anything. Can anyone suggest something I may have missed?
That is Core code trying to use a Core function. You have almost certainly had a problem with the transfer. 1. Very carefully, re-upload all of the files. I expect some file is missing or corrupt. 2. And make sure that all of your permissions are correct. It would probably be a good idea to disable plugins and switch to a default theme as well. Since you can't get into the backend you will need to remove or rename the theme and plugin folders via FTP. Since you just transfered, I am assuming that you have good backups.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "themes, admin, database" }
Sanitize Disqus API results? Can I trust the results from the Disqus API, not to include evil scripts? Can I find information somewhere. Would you sanitize the JSON data, that is returned? Official answers?
Assuming you're talking about the body of a comment, there's nothing to worry about. We already sanitize comment and thread messages.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "api, sanitization, disqus" }
base directories / URL Is there a way to handle base directories for taxonomies that result in a 404. For example my URLs are: < < but the taxonomies / base directories above result in 404. Can they be redirected to a taxonomy index page (which I may need to create) for example without impacting the child directory (post) or is there a better option. If so how? I suspect the answer lies in redirects but I'm not confident.
You can manually create pages named `category` and `app` in admin under the `Pages` menu, and use a custom page template for each to list out taxonomy terms or whatever you need. EDIT - 301 redirect a request that matches the `pagename` rewrite to another page: function wpa_parse_query( $query ){ if( isset( $query->query_vars['pagename'] ) && 'apps' == $query->query_vars['pagename'] ){ wp_redirect( home_url( '/other-page/' ), 301 ); exit; } } add_action( 'parse_query', 'wpa_parse_query' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "taxonomy, redirect, urls" }
how to hide home nav link in wordpress I'm trying to hide the home navigation link from the theme boilerplate that I downloaded from underscores.me. Wordpress codex says that its not shown by default, but whether I do this: <?php wp_page_menu( array( 'show_home' => true ) ); ?> Or this: <?php wp_page_menu( array( 'show_home' => false ) ); ?> It still shows the home page nav link. When I don't call the `wp_page_menu` function it doesn't display the menus so I know its the one that's outputting it. Any ideas what's wrong and what else could I try? Thanks in advance!
If all else fails, you could use a CSS approach. Try `display: none;`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, navigation" }
How to hide first gallery for every post? I'm using galleries for attaching images, so the very first gallery for every post is used to generate a slider and nothing more. That's why I don't want to see it in post's conent. Let's say I have a single post that looks like this: [gallery ids="1,2"] // hide [gallery ids="3,4"] // display [gallery ids="5,6"] // display Is there some way of blocking the very first gallery from the content for every post? #gallery-1 { display: none !important; } works good but is ugly as hell :) Also it only hides the gallery but it's still there, same goes for it's JS.
You could use `preg_replace()` but I think it's much easier to overwrite the `$output` via the `post_gallery` filter and then remove the filter after the first run: /** * Remove the output of the first gallery * * @param string $output * @param array $attr * @return string $output */ function wpse125903_remove_the_first_gallery( $output, $attr ) { // Run only once remove_filter( current_filter(), __FUNCTION__ ); // Override the first gallery output return '<!-- gallery 1 was here -->'; // Must be non-empty. } add_filter( 'post_gallery', 'wpse125903_remove_the_first_gallery', 10, 2 ); This should remove only the first gallery in your posts.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, gallery, count" }
Importing Existing Users with Passwords I have an existing legacy PHP site of 15000 users with base64 hashed passwords , I would like to import all these users into the new wordpress site with their passwords , What would be the best approach to realize this? Praveen
You can use `wp_insert_user`. Since your old database has passwords in base64, you can easily get the original password string using `base64_decode`. $new_user_data = array( 'user_pass' => 'password',//pass your decoded password string 'user_login' => 'username',//pass your username 'user_email' => 'email', 'first_name' => 'firstname', 'last_name' => 'lastname', 'role' => 'author'//if you want to specify a different role other than default one ); wp_insert_user( $new_user_data ); You need to format your old data in csv or xml or text file and read and pass them accordingly. And don't try to import all 15000 users at once. Do this in several parts. Also `sleep()` function will be quiet good to give the server some rest.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "users, import, password" }
Multitenant with a single site **What are the best practices to create a multitenant enviroment in wordpress?** I've created an app with wordpress. Now i would like to make it as a multitenant solution. I've ended up with two options: * Create a multisite registration and use the wp network solution (each tenant is a site - a lot of dbs / separated content ) * Single site and use authors on queries (tenant content not well separated / single wp db) The app is the same for everyone, all interfaces, content types, available options are the same.
Before I learned about Wordpress network solution I went with option two - setting up certain privileges to users to be able to view and edit content only authored by (and for) them. That can be accomplished by using almost any WP plugin that allows you to change permissions per user, and a few functions that will change how and when things like attachments, post/page count, media library appear. It's manageable, but also a bit of a hassle. Having recently done a similar thing with WP network, I have to say it's an easier and cleaner solution that already handles most of the issues you would come across using single WP installation. Note: Network doesn't require separate databases from you, merely tables under the same database. That means that you can query content from other sites (blogs) to avoid its repetition. All in all, I'd say that for this purpose: **Wordpress Multisite Network > Single WP installation**
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite" }
Need edit profile link in the menu for logged in users I have a page called edit profile, i have installed the profile builder plugin,so the users can edit their profile from front end, if the user is logged in i want to show the edit profile and logout else it is login. how can i achieve that? i am using wp-bootstrap responsive theme, i am new in wordpress development any one please help me.Do i need to change any thing in the header.php file?
You can get the current user's info by using `wp_get_current_user()` and then get the profile edit link by using the `user's ID` as following: function wpse_125929_login_logout( $items ) { if ( is_user_logged_in() ) { $current_user = wp_get_current_user(); $profile_edit_url = admin_url( 'user-edit.php?user_id=' . $current_user->ID ); $profile_link = '<li><a href="' . $profile_edit_url . '">Edit Profile</a></li>'; $logout_url = '<li><a href="'. wp_logout_url() .'">Logout</a></li>'; $items = $items. $profile_link. $logout_url; } else { $login_link = '<li><a href="'. site_url('wp-login.php') .'">Log In</a></li>'; $items = $items. $login_link; } return $items; } add_filter( 'wp_nav_menu_items', 'wpse_125929_login_logout' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugin development, login, profiles, logout" }
WordPress fails to embed video URL WordPress or my theme fails to embed this video URL: ` but works with this URL: I need to get rid of the youtube control buttons in the preview, but cannot use embed or the iframe because that just creates an hyperlink. Any ideas? WP version 3.7.1
Having `&controls=0` instead of `?controls=0`solved the issue for me.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "embed, youtube" }
find posts with exactly 3/4 categories I see wordpress gives you opportunity for searching posts with exactly N categories...so i tried by myself and produced this code... $catIDs = get_cat_ID( $cat_name='CategoryName1' ); $catIDs .= ',' . get_cat_ID( $cat_name='CategoryName2'); $catIDs .= ',' . get_cat_ID( $cat_name='CategoryName3'); echo "$catIDs </br>"; $my_query = new WP_Query( array( 'category__and' => array($catIDs) ) ); if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post(); ?> <li> <a href="<?php the_permalink(); ?>"> <?php the_ID(); ?> </a> </li> <?php endwhile; endif; wp_reset_postdata(); ?> if i replace the array($catIDs) with 1,2,3 (the ID of the category) this solution works....why with the variable $catIDs it doesn't? and how can i make this solution dynamic (i have a form and i would pass the data in this form -category name/ID in this case)
**Make sure you are providing correct category names into the function get_cat_ID().** <?php $catIDs = array(); $catIDs[] = get_cat_ID( 'CategoryName1' ); $catIDs[] = get_cat_ID( 'CategoryName2' ); $catIDs[] = get_cat_ID( 'CategoryName3' ); $my_query = new WP_Query( array( 'category__and' => $catIDs ) ); if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post(); ?> <li> <a href="<?php the_permalink(); ?>"> <?php the_ID(); ?> </a> </li> <?php endwhile; endif; wp_reset_postdata(); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories" }
Can plugin variables cause conflict? I write a wordpress plugin. My plugin code in inside a class. if (!class_exists("Pluginname")) { class Pluginname { ... } } if (class_exists("Pluginname")) { $obj = new Pluginname; } Question: What if `$obj` is already used in Wordpress code or in another plugin? Can this be a potential source of conflict? If so, what to do?
They can. Say you have plugin one, with only this: // Plugin one $variable = "henk"; And then you have plugin two, with only this: // Plugin two echo $variable; And now you activate these plugins, you will probably see the variable of plugin one echo'd by plugin two (at least it did here, but I don't know what determines the sequence). It's probably best to use a sort of prefix like $my_plugin_variable if you're not using it inside a function or class.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "plugins" }
How to check a filter are applied I want to apply this filter from this question. add_filter( 'the_content', 'pre_content_filter', 0 ); function pre_content_filter( $content ) { return preg_replace_callback( '|<pre.*>(.*)</pre|isU' , 'convert_pre_entities', $content ); } function convert_pre_entities( $matches ) { return str_replace( $matches[1], html_entity_decode( $matches[1] ), $matches[0] ); } But it seems there is no effect. So I want to check if the function `pre_content_filter` is really applied. How can I do it? I've tried `debug-bar` and `debug-bar-extender`, but I couldn't find if I can do it.
You can use `has_filter()` to check for registered filers. Example: add_filter( 'the_content', function( $content ) { if ( has_filter( 'the_content', 'pre_content_filter' ) ) return 'pre_content_filter() is active<br>' . $content; return $content; }, -1 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "filters" }
Cron jobs repeating themselves If I have a function set to run every 5 minutes via a WP cron job, and I have only one visitor during a day, does his visit trigger just one run of that function or all the runs that have been amassed since the last visit? The cron job I have runs a function that fetches feeds from another site.
The wp_schedule_single_event function in cron.php (< has a comment which says: // don't schedule a duplicate if there's already an identical event due in the next 10 minutes So I'd say that no it won't trigger lots of calls for earlier in the day.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp cron, cron" }
Do WordPress cron jobs slow down page loading? If a user visits a site and his visit triggers a cron job that is quite intensive, the page load speed will be slower for him right? As I understand the page doesn't wait for the cron job to execute before loading, but since the cron job would be running in parallel, it might still be the case that the page loads slower since the server is busy right?
Short answer - **Nope**. Any page request initializes the scheduled queue. It's just an initialize request. Wp-cron request is a standalone request. > so requesting URL `/somepage` you just initialize request to `/wp-cron.php` However - If cron event doesn't work really well (it's has 1000 db queries e.g. or its requesting a some really long-to-respond resource), or both, or re-scheduling cron event for each request... just like any other http request it will eat resources, CPU performance, memory, etc... if it eats enough resources, your page will become slower.
stackexchange-wordpress
{ "answer_score": 12, "question_score": 10, "tags": "wp cron, cron" }
Will deleting WP's code in .htaccess cause problems? I need to use the following redirect on my site: RewriteEngine on RewriteCond %{HTTP_HOST} name.com RewriteCond %{REQUEST_URI} ^/(1[0-9]{3}|200[0-9]|201[0-3]) RewriteCond %{REQUEST_URI} !/2013/12 RewriteRule ^([0-9]{4})/([0-9]{2})/(.*)$ [NC,R=301] However, it only works if I delete the code Wordpress put in my .htaccess (I've tried putting it both before and after this code with no luck): # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress What sort of problems is this going to cause if I delete it permanently? And is there some way around this?
Adding the `[L]` flag to the `[NC,R=301]` piece (ie, `[NC,R=301,L]`), which tells the RewriteEngine that the RewriteRule is the last one for the block of `RewriteCond`s, apparently solved the problem. RewriteEngine on RewriteCond %{HTTP_HOST} name.com RewriteCond %{REQUEST_URI} ^/(1[0-9]{3}|200[0-9]|201[0-3]) RewriteCond %{REQUEST_URI} !/2013/12 RewriteRule ^([0-9]{4})/([0-9]{2})/(.*)$ [NC,R=301,L] # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> ### Reference * Apache's URL Rewriting Guide and `mod_rewrite` documentation (particularly the section on `RewriteRule`)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect, htaccess" }
new_excerpt_more link not working properly My "Read More" button is linking to the current page page instead of the excerpt page it is suppose to be linking to. Here is my function in function.php file: function new_excerpt_more($more) { global $post; return ' <a href="'. get_permalink($post->ID) . '"> ...Read More</a>'; } add_filter('excerpt_more', 'new_excerpt_more'); This is occurring in in excerpts being displayed from a custom walker for wp_list_pages.
Global `$post` variable is filled on by running post through the loop (`the_post()` method or function, `setup_postdata()` function). If you look at the source for `Walker_Page` it is not running a loop and so does not make posts' data available through `$post`. Since `excerpt_more` is not provided with info on the post either, you would need to track post data on your own and access it inside your filter function.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions, excerpt, wp list pages, read more" }
Custom Post Type Rewrite Rule My theme uses the following code: 'rewrite' => array('slug' => $this->safe_name . '-detail'), which produces this slug: I need to get rid of the 'estate-detail' part so I changed the rule to just: 'rewrite' => array('slug' => ' '), This produces the slug as: How do I get rid of the double forward slash?
add_filter( 'post_type_link', 'filterslash_post_type_link', 11, 2); function filterslash_post_type_link( $post_link, $post ){ $post_link = home_url("/$post->post_name/"); return $post_link; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, url rewriting, slug" }
Listing all selected terms for custom taxonomies on a post I'm running a query on a custom post type to display on a page. The custom post type has multiple custom taxonomies. Each taxonomy is not required. I want to display only the taxonomy terms selected, and not the others. How would I achieve this? $args = array( 'post_type' => 'inspirations', 'posts_per_page' => 10 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); echo '<div class="inspirations-post '. wp_get_post_terms($post->ID, 'collections') . '">'; the_title(); echo '<div class="entry-content">'; the_excerpt(); echo '</div>'; echo '</div>'; endwhile; Right now this returns Array() when printed. I'm guessing I need to break apart the array somehow.
$args = array( 'post_type' => 'inspirations', 'posts_per_page' => 10 ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); $collections = ''; foreach ( (array) wp_get_post_terms( get_the_ID(), 'collections') as $collection ) { if ( empty($collection->slug ) ) continue; $collections .= ' collection-' . sanitize_html_class($collection->slug, $collection->term_id); } echo '<div class="inspirations-post '. $collections . '">'; the_title(); echo '<div class="entry-content">'; the_excerpt(); echo '</div>'; echo '</div>'; endwhile;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy" }
Route to custom file I would like to create a custom file inside an existing WordPress theme. But I'm not sure how to route to it, and tell WordPress that the route named `www.mysite.com/custom` should redirect to the `custom.php` file inside my theme's directory.
This is just simple. First create a page and use slug for it as `custom`. And then rename you php file to `page-custom.php` and that would be it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, routing" }
How do you get the docroot directory? I'm trying to include a file in the docroot when I'm in the admin area. (Yes, I know this is bad form: I'm only doing it for debugging purposes.) How do I get the fully qualified docroot directory?
// server document directory $dir = $_SERVER['DOCUMENT_ROOT']; // wordpress install directory $dir = ABSPATH; to include safely with wordpress add_action('plugins_loaded', 'load_a_file'); function load_a_file(){ if( is_admin() ){ $dir = $_SERVER['DOCUMENT_ROOT']; include_once( $dir . '/file.php' ); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "debug" }
How to hide "post" link from the admin bar After studying several blogs, I figured out that to add/edit/delete admin bar items need to do something like this: add_action( 'wp_before_admin_bar_render', 'wpse20131211_admin_bar' ); function wpse20131211_admin_bar() { global $wp_admin_bar; $wp_admin_bar->remove_menu('wp-logo'); $wp_admin_bar->remove_menu('comments'); } But with this I can remove comments links, wp logo etc. But can't remove the **Post** link under the **\+ New** menu on the admin bar. !post link under admin bar I tried with: $wp_admin_bar->remove_menu('post'); and similarly with `'posts'`, `'add-post'` etc. But failed.
Try this: $wp_admin_bar->remove_node( 'new-post' ); It will remove **Post** link under the admin bar's **\+ New** link. **LEARN MORE:** **`remove_node()`** \- WordPress Codex
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "admin bar" }
Is template name always same as directory name? When creating child theme, I must write like this. /* Theme Name: 2012 Child Template: twentytwelve */ Is that `Template` name is always same as directory name? Or is it defined somewhere else?
According to the codex > The Template is the directory name of the parent theme > > ... If you want to make a child of a theme with the directory name example-theme-name, then you would use Template: example-theme-name. So yes its always the name of the parent theme directory.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "templates" }
Changing pagination list class `paginate_links()` function returns unordered list with class named "page-numbers". How can I change this class? EDIT Currently, I am using the band-aid method below. $return = paginate_links( $arg ); echo str_replace( "<ul class='page-numbers'>", '<ul class="pagination">', $return ); Is there any better way?
`paginate_links()` doesn't offer a parameter and there are no hooks - see source \- available to change the class(es). Which means you can do it like you have done it or you create your own pagination function based on `paginate_links()`.
stackexchange-wordpress
{ "answer_score": 12, "question_score": 21, "tags": "pagination, paginate links" }
Save wp_editor() content as option I'm having some troubles with a extra feature i'm writing for my theme. The admin should be able to make some special posts, those posts are stored as an option. The options are atored as an array and WP makes it's own json for arrays. So, the user has a wp_editor(), and the array stored looks something like this: array( 'title' => 'My title', 'content' => 'Look at my cat! <img src="mycat.jpg" />', //Generated by wp-editor 'signature' => 'My name' ); The thing is, when an image is added to this content, the image string is quite badly escaped. When i'm trying to get this content i get it as <img src="\"mycat.jpg\"" /> instead of <img src="mycat.jpg" /> How can i store content like this in the wp-options table so i can get it right when i try to get the content?
If you just want to get rid of the `\` characters in the string that's returned, you can use PHP's `stripslashes()`: $content = stripslashes( $content ); I'd recommend doing this on output rather than on input; WordPress adds the slashes as it sanitizes your data on insert, per `update_option()`'s Codex page, > The `$option` (option name) value is escaped with `$wpdb->escape` before the `INSERT` statement. See Data Validation for _way_ more information.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "wp editor, options" }
Help setting up a sql query I need to list out specific custom field items that contain an associated custom field entry. For example, the custom fields are named "type" and "food". I would like to list out all of the breakfast foods. "Breakfast" being the "type" custom field and "bacon", "eggs", "biscuits" being the "food". Right now, I have this query, but it lists out every type of food when I need it to list out only the breakfast types. Would I need to add "WHERE meta_value = 'type' AND meta_key = 'breakfast'" somewhere? I've tried a few places and nothing would work. <?php $metakey = 'type'; $stocktypes = $wpdb->get_col($wpdb->prepare("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = %s ORDER BY meta_value ASC", $metakey) ); if ($stocktypes) { foreach ($stocktypes as $stocktype) { echo "<option value=\"" . $stocktype . "\">" . $stocktype . "</option>"; } } ?>
Ok, if i understand you clearly, then this is the solution // first get the post ids that have the breakfast food type $post_ids = $wpdb->get_col( "SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = 'type' AND meta_value='Breakfast'" ); // now get the food names $stocktypes = $wpdb->get_col( "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'food' AND post_id IN (". implode(',', array_map('absint', $post_ids) ) .")" ); if ($stocktypes) { foreach ($stocktypes as $stocktype) { echo "<option value=\"" . $stocktype . "\">" . $stocktype . "</option>"; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, mysql, wpdb" }
Displaying Results From Custom Taxonomy Query I have created a custom taxonomy Region and I would like to query this taxonomy for all results and display them. My query is: $args = array( 'tax_query' => array( array( 'taxonomy' => 'region', 'field' => 'slug', 'terms' => array( 'north', 'east', 'west', 'south' ) ) ) ); $query = new WP_Query( $args ); How do I then display this result as html? Something along the lines of this: <li class="location large-3 columns"> <img src="<?php echo get_template_directory_uri(); ?>/images/region1.jpg" alt="" /> <span class="location-title">TAXONOMY TITLE HERE</span> </li>
$regions = get_terms('region', array('hide_empty' => false) ); foreach( $regions as $region ){ ?> <li class="location large-3 columns"> <img src="<?php echo get_template_directory_uri(); ?>/images/<?php echo $region->slug; ?>.jpg" alt="" /> <span class="location-title"><?php echo $region->name; ?></span> </li><?php }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, wp query, query, taxonomy, terms" }
add_rewrite_rule to search Newbie WordPress developer here. I need to map a WordPress URL like this `www.example.com/user/Username` to a search result based on that Username I already have the page that makes the search with the url `www.example.com/search-results/?name=Username` In the `functions.php` I have add_action( 'init', 'add_username_rules' ); function add_username_rules() { global $wp_rewrite; add_rewrite_rule( "user/([^/]*)", "search-result/?name=$matches[0]", "top" ); $wp_rewrite->flush_rules(); } But this is not working and the rule is going to `non_wp_rules`.
That's going to the non wp rules because you're not mapping the URL to the index.php page format. If you want it to be a WP rule, then you need to start the destination with index.php and include the query string to define what you want the query to contain. So if you wanted it to go to a specific Page, for example, then you could set it as: `index.php?page=123&name=$matches[0]` WordPress rewrite rules map the "pretty" url formats into the "default" url formats only. They're not full implementations of the htaccess rewrite system.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rewrite rules" }
Disable comments feed, but not the others I'd like to customize my WordPress blog in such a way that it is no more possible to access the comments feed. Other feeds should still be available, and it should still be possible to add comments to any article. I tried to find a plugin to do this, but what I found is a all or nothing feature, without the possibility to finely adjust which feeds are allowed and which are not.
function remove_comment_feeds( $for_comments ){ if( $for_comments ){ remove_action( 'do_feed_rss2', 'do_feed_rss2', 10, 1 ); remove_action( 'do_feed_atom', 'do_feed_atom', 10, 1 ); } } add_action( 'do_feed_rss2', 'remove_comment_feeds', 9, 1 ); add_action( 'do_feed_atom', 'remove_comment_feeds', 9, 1 );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "feed" }
How to display sub categories under products page using woocommerce with mystile theme I have been trying to display my product subcategories after you click on the parent category but to no avail. It simply shows all my products for instance: Main product- Pacifier Clips, Subcat- NFL Pacifier clips, but once you click on main product(Pacifier Clip) it shows all Pacifier clips from every category without giving you the option to choose which category. I have tried the settings under catalog in woocommerce but with no success, I have ensured that my subcategories are linked to my parent category. I'm all out of ideas of what to do. I would be willing to add code to resolve the problem but am not sure which php file to edit under woocommerce. Anyone have any idea? Site address: www.innovativehouseholddesigns.com
Go to Woo-commerce Product Category Page. Find the category **PACI-CLIPS** , click on _edit_. And from the edit page, Set `Display type` to `Subcategories`.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins" }
Custom Meta Title for Custom Post Type I have several custom post types that need to display different values within `<title></title>` in the header. I understand for the home page, posts, categories, and pages you can use.. if (is_home()){ } elseif (is_category()){} elseif (is_single() ) {} elseif (is_page() ) {} My question is, how would I do the same for individual CPTs (eg. songs, videos, news..etc)
The template tag to check CPTs single page - is_singular. So you can use `is_singular('songs')` to check if the current post page is a single page for post type `songs`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, title" }
Where do I go to change the position of the style.css? My CSS style.css file is in my theme folder. I would like to put it in a CDN. How do I change the link element that loads the css? I am using as a base the 2013 wordpress theme.
Add the following code to themes functions.php file. Replace '` to your stylesheet file uri on CDN. add_filter('stylesheet_uri', 'my_custom_stylesheet_location'); function my_custom_stylesheet_location( $stylesheet_uri ){ return ' }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css" }
Combine the results of two loops I currently have these 2 loops running on a single page $related = p2p_type( 'artist_to_song' )->my_get_related( get_queried_object() ); $features = p2p_type( 'song_to_feature' )->my_get_related( get_queried_object() ); if ( $related->have_posts() ) : while ( $related->have_posts() ) : $related->the_post(); //content endwhile; wp_reset_postdata(); endif; if ( $features->have_posts() ) : while ( $features->have_posts() ) : $features->the_post(); //content endwhile; wp_reset_postdata(); endif; Is it possible to combine the results of these loops into one so that all the posts are listed in chronological order as opposed to the results of `$related` being followed by `$features`.
Yes it is. First you have to combine the results in one array: $all_posts = array_merge( $related->posts, $features->posts ); Now, let's sort the array items by date: usort( $all_posts, function( $a, $b ) { return strcmp( $b->post_date, $a->post_date ); } ); Finally, do the loop: global $post; foreach ( $all_posts as $post ) { setup_postdata( $post ); // use the template tags here: the_title(), the_content(),… } wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "loop, plugin posts to posts" }
Grab last part of the url inside rule I have an url like this ` And I have one rule to map it into a search page, but I want to grab that Pimpampum inside the rule. So that I can call the search for that name add_rewrite_tag("%u%", '(.*)'); add_rewrite_rule( 'username/(.+?)$', "index.php?pagename=search-result&u=".$matches[1], "top" ); But I can't see how to grab the last part of the url. Any help? Thanks
doesn't it work `get_query_var('u')` to grab the variable ? Also you need to use - `"index.php?pagename=search-result&u=". '$matches[1]'` , single quote surrounding `$matches[1]`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rewrite rules" }
Wordpress 3.8 - Dashboard 1 Column Screen Options With the new Wordpress 3.8 under Screen Options they seem to have misplaced the "Columns" feature where you could put your widgets into 1 Column, 2 Columns, 3 Columns, or 4 Columns. My question is how to I force my Dashboard Widgets to only be 1 column, or in other words, take up the whole width of the screen versus just a portion of the screen?
Another solution is to add the columns setting back to the settings. function wpse126301_dashboard_columns() { add_screen_option( 'layout_columns', array( 'max' => 2, 'default' => 1 ) ); } add_action( 'admin_head-index.php', 'wpse126301_dashboard_columns' ); !Screenshot of the Screen Layout setting There is a related Trac ticket: #26354
stackexchange-wordpress
{ "answer_score": 31, "question_score": 25, "tags": "widgets, dashboard, screen options, screen layout" }
Theme information in style.css being corrupted I am customising someone else's theme to allow the website owner to edit more regions than she could previously. I copied the theme into a new folder, with a different folder name to the original. I edited style.css, and replaced the theme information with: /* Theme Name: Customisable SuperBaby & Ted Author: Steve Doig Author URI: Description: Modified version of SuperBaby & Ted to allow edits to the home page and footer navigation. Version: 2.0 */ Yet when I upload style.css to the theme's folder, I see this in Appearance > Themes: !enter image description here I've added a blank line between each line, with no difference. I've copied this info into a new Notepad, copied from that Notepad, and pasted back into the original Notepad with no difference. Can you see what is going on here?
I use Notepad2 to edit style.css I opened it in Notepad++, and there were extra line breaks on every line. I opened it in Dreamweaver CS6, selected Commands > Apply Source Formatting, and all extra line breaks were removed. I uploaded it, and it now views normally in the browser (Originally viewing style.css showed the line breaks were gone). The Theme information is now displaying properly. Note: the style sheet was displaying properly in Notepad2 originally. Perhaps Notepad2 handles line breaks differently. Thanks for your help.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "themes, css" }
Form submission to another page returning 404 error I'm modifying a form plugin, and trying to have it submit to another page chosen by the user. Right now the page it submits to is `page_id=6`. If I navigate to this page myself, it prints `Array()`. When I submit the form, I get a 404 error although the url matches. `page_id=6` uses the shortcode `[convertable]` to include this code: <?php echo "<pre>"; print_r($_POST); echo "</pre>"; ?> I'm testing in on a WPMU install. You can see the form here Any ideas on what's going wrong?
you're using `name='name'` for your first input. That breaks it. Change the name to something else as suggested above, prefix everything. `name='my-prefix-name'`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, shortcode, forms, 404 error" }
Get sticky post from category? I have parent category is Game `cat_id=42`. Child categories are : acrade, causual,.... I want show a top game module in mainpage template, it will show 10 sticky post from game category. This my code : <?php $args = array( 'cat' => 42, 'posts_per_page' => 10, 'post__in' => get_option( 'sticky_posts' ), ); query_posts( $args ); ?>
Use the below code in the mainpage template to show the sticky posts. <?php $args = array( 'cat' => 42, 'posts_per_page' => 10, 'post__in' => get_option( 'sticky_posts' ), ); // The Query $the_query = new WP_Query( $args ); // The Loop while ( $the_query->have_posts() ) { $the_query->the_post(); echo '<li>' . get_the_title() . '</li>'; } The above will print the title of the sticky posts
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories, sticky post" }
Show recent posts in single-post page I'm trying to show recent custom posts in `single-events.php` I can make it work by using `get_posts` what I don't know how to do is exclude the post that is active so if I'm on 'Event 1' just now using the code below it will show 'Event 1' in the 'Recent Events' section. How do I get around this? <?php $args = array( 'post_type' => 'events', ); $myposts = get_posts( $args ); foreach ( $myposts as $post ) : setup_postdata( $post ); ?> /* EDIT */ I was missing this: `'exclude' => $post->ID`
The function `get_posts()` accepts a parameter 'post__not_in', which allows you to specify an array of post IDs to exclude from the query. `get_posts()` is just a wrapper for `WP_Query`, so the documentation for this parameter can be found here. When inside the loop (such as inside `single-events.php`) you can retrieve the current post's ID with `get_the_ID()` (codex). So the following should work: $args = array( 'post_type' => 'events', 'post__not_in' => array( get_the_ID() ), ); $myposts = get_posts( $args );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "archives, get posts, recent posts" }
Why is 'pre_get_posts' having no effect? I'm trying to use pre_get_posts for the first time without any success. It's a very simple piece of code on the index page of an otherwise empty theme, purely to get the hang of the action hook: function just_one( $query ) { $query->set( 'posts_per_page', 1 ); } add_action( 'pre_get_posts', 'just_one' ); From what I have read, I cannot see anything wrong with this, but when I run this below it: echo get_query_var( 'posts_per_page' ); it displays the default '10', rather than the '1' I was expecting. Am I doing something wrong? The index page is entirely empty apart from the above code. Cheers for any help.
> ... It's a very simple piece of code on the **index** page of an otherwise empty theme... If you are running this code on the **_index page_** of your theme and expect it to effect the main query, then you are adding the action too late. The main query runs well before your theme template loads. You will need to put that code in `functions.php` in your active theme or in a plugin and use some conditional logic to make sure that it runs only where you want it too. For example... function just_one( $query ) { if ( $query->is_main_query() && $query->is_front_page() ) { $query->set( 'posts_per_page', 1 ); } } add_action( 'pre_get_posts', 'just_one' ); I don't really know what the `if` condition should be. Refer to the Codex page already linked to for the conditions available.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "pre get posts" }
Check if custom taxonomy has posts with get_categories() I'm using **get_categories** to list all the terms of my taxonomy " **genre** ", but I have other taxonomy called " **brands** ". In Brands page ( **taxonomy-brands.php** ) I need to return all the posts from the brand and the genre they're related. **For example, I have a taxonomy page for Ferrari:** . Brand name: Ferrari .. Genres: Red, Yellow **But I also have a taxonomy page for Wolkswagen:** . Brand name: Wolkswagen .. Genre: Blue, Green The problem is that Ferrari page, is also listing "Blue" and "Green", even if Ferrari doesn't have any posts related to Blue and Green. Finally, is there any way to hide "Blue" and "Green" when they're not used? Here is what I got so far: < If you need a visual example: \- "Sucos" and "CD" should not appear, since this brand only has posts with "Macarrão Instantaneo".
Category objects returned by API have count of posts on them in `count` field. You should simply check that and skip rest of the iteration for those that have no posts. Something like: foreach( $categories as $category ) { if( 0 == $category->count ) { continue; } Scratch that. If I get it right this time what you really need is to check if you got any posts before you output category header. Something like (don't use `query_posts()` by the way, it's trouble): $stuff = new WP_Query( $args ); if ( $stuff->have_posts() ) { ?><a href="#" class="list-group-item active"><?php echo $category->name; ?></a><?php while ( $stuff->have_posts() ) : $stuff->the_post(); // posts output endwhile; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy" }
Displaying categories items among posts I'm making a website with lots of custom posts as well as custom hierarchical taxonomies. Default index (archive) page is made of bricks with photo, title and excerpt from posts. And here comes the problem, cause those index/archive pages mustn't contain only posts items (bricks), it should also contain (among the normal post items) bricks showing sub-categories of current. Is it a good way of doing such a thing using categories, and if it is - how to achieve it? EXPLANATION EDIT: By bricks i understand floating containers, just the visual representation of post (or category) data. Floating thumbnails with descriptions. Category archive page would contain items of two types: 1) posts located in current category (not subcategories) and 2) subcategories of current category. It'd be kind like files and folders structure.
Okay, after a research of a matter, i came to the conclusion. My post types would either be the category posts with no data (parent containers) or a child posts - standard articles. My template will check if the post does have any children - if not - it will display the post itself, and if yes - it will display gathered bricks (thumbnailed excerpts) of them. Taxonomies do not have anything to do with it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, categories, loop, custom post type archives, archive template" }
Automatically assign taxonomy term if custom meta value exists I currently have a custom meta field for adding a video url to the post. I'd like for the existing taxonomy term "video" to be automatically assigned to the post upon saving if the meta field has any value.
You should hook onto the save_post action. add_action( 'save_post', 'add_video_taxonomy' ); function add_video_taxonomy( $post_id ) { // you should check if the current user can do this, probably against publish_posts // you should also have a nonce check here as well if( get_post_meta( $post_id, 'video_url', true ) ) { wp_set_post_terms( $post_id, 'video', 'your_custom_taxonomy_name', true ); } }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "custom taxonomy, custom field, metabox, terms" }
Displaying popular posts I wanted to write a query to display, 3-4 top popular post, in my sidebar with a small thumbnail size image of the post. I tried looking at archives widget, but it only displayed links. (thought, i could copy the code from there), how do i get to have my desired result?
You can attach images to each post using "featured images" by first enabling featured images for your theme using add_theme_support('post-thumbnails'), and get_the_post_thumbnail() to display images. For example, to list 4 most commented posts with their featured image and title, you can do something like this: $posts = get_posts( array( 'posts_per_page' => 4, 'order_by' => 'comment_count' ) ); foreach ($posts as $post) { get_the_post_thumbnail($post->ID) echo $post->post_title; } Read about WP_Query for more querying options. To get more advanced measurements, you may want to look into a plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "query" }
ACF Image Object Sizes Issue on Multisite I am using Advanced Custom Fields and have added an image with the return value being an image object. In my theme I if I dump the values of the object all the URL's for sizes are the same regardless if it is `thumbnail`, `medium`, or `large`. I am doing this on a multisite. Here is what the image object looks like: ( [id] => 123 [alt] => [title] => My image [caption] => [description] => [mime_type] => image/jpeg [url] => [width] => 5400 [height] => 3600 [sizes] => Array ( [thumbnail] => [thumbnail-width] => 150 [thumbnail-height] => 100 [medium] => [medium-width] => 300 [medium-height] => 200 [large] => [large-width] => 1024 [large-height] => 682 ) )
The issue was the GD was not installed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, images, advanced custom fields" }
add_theme_support not outputting thumbnails so, i wanted to thumbnails in my query and i came across `add_theme_support`, it says you have to have that to enable actions such as `thumbnail`, so i put the following in my functions function pippin_add_thumbnail_support() { if(!current_theme_supports('post-thumbnails')) { add_theme_support('post-thumbnails'); } } add_action('init', 'pippin_add_thumbnail_support'); Even after that code, my query doesn't generate a post thumbnail, when my query is <?php $posts = get_posts(array('posts_per_page' => 4)); foreach ($posts as $post) { if( has_post_thumbnail()){ get_the_post_thumbnail($post->ID,'thumbnail'); echo $post->post_title; } Am i missing something, or doing something wrong?
You need to echo the get_post_thumbnail in order for it to output. echo get_the_post_thumbnail($post->ID,'thumbnail');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, post thumbnails" }
How to deal with spam comments and distinguish them from non-spam comments? I have something like 10000 comments. They are probably all spam except for one or two. And they are all waiting for me to approve them. Is there a free solution to this issue? Thank you!
Delete them all. I don’t think a few comments are worth so much of your time. To clean up the entire table, open a SQL console (the plugin Adminer has an UI for that) and type: TRUNCATE table wp_comments You might have to change the name if you are using an other prefix than `wp_`. Or … you could use an existing anit-spam plugin with open source (Antispam Bee and/or T5 Spam Block for example) and run all your comments through their filters. In a secound round, find all IP addresses marked as spam already and delete all comments with matching IP addresses. That should cover most of the spam.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "comments" }
Multiple parent categories I'm new to wordpress. I want to create some main categories and 5 sub categories for each main category. Sub categories will be same for both main categories. E.g main categories will be "USA","Canada" etc. sub categories will be "places","photos" etc. Is it possible to make this with single wordpress or do i need to install another wordpress for each main category?
You may want to also consider using multiple taxonomies, not just one- categories. One taxonomy for location, another taxonomy for content type, then you won't have duplication of sub-categories. see taxonomies in codex for more info.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, multisite" }
How to change admin bar color scheme in MP6 / WP 3.8 front end? I need to change default color scheme for all users. The admin bar on my site is vidibile for all users including guests. The default black color scheme isn't beauty with my design and I would like to change it with cofee scheme. Is there any way to do this? I already found add_filter('get_user_option_admin_color','change_admin_color'); function change_admin_color($result) { return 'coffee'; } But it disable feature to choose another color scheme for users. And first of all it work only for logged in users.
At the moment (3.8) color schemes **do not apply to admin bar at front end** at all, even if user is logged in and has non-default scheme selected. The shortest way would probably be to force enqueue color scheme at front end: add_action( 'wp_enqueue_scripts', function () { wp_enqueue_style( 'color-admin-bar', admin_url( '/css/colors/coffee/colors.min.css' ), array( 'admin-bar' ) ); } ); Note that core chose not to do it, so it is untested and there is risk of style incompatibilities and such.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 5, "tags": "theme development, customization, wp admin, profiles" }
Display the current post author and his url in the post header I'm making some changes in my theme. I want that when they visit a Post the header should contain the post author and his URL. right now I'm using this: echo '<a href="'.get_author_posts_url().'">'.get_userdata($posts[0]->post_author)->data->display_name.'</a>; the auhtor's display name is working correctly, but the link is going like www.mysite.com/?auhtor=0 instead of this (for example) www.mysite.com/?auhtor=36 so this is the code in the header <a href=" name</a> instead of this: <a href=" name</a> by the way: I'm doing this outside a loop.
for anyone who's having this problem,this is the code I used: echo '<a href="'.get_author_posts_url(get_userdata($posts[0]->post_author)->data->ID).'">'.get_userdata($posts[0]->post_author)->data->display_name.'</a>';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, theme development, author, custom header" }
How can I set wp_dropdown_users so that it shows only authors? I want to list in a drop-down box all users who have role "author" How can i do it? Thank you
you can create a function which gives you all users which have role author in a drop down list. **Note** : It is a dummy example modify it as you want( put this function in `functions.php` or custom `plugin` ). **Use** : Call this function any where in theme like `<?php ravs_author_dropdown_list(); ?>` function ravs_author_dropdown_list() { // query array $args = array( 'role' => 'author' ); $users = get_users($args); if( empty($users) ) return; echo'<select>'; foreach( $users as $user ){ echo '<option value="'.$user->data->user_login.'">'.$user->data->display_name.'</option>'; } echo'</select>'; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "users, author" }
WooCommerce product and terms count I need to display two things: 1. Total number of published WooCommerce products 2. Total number OF attributes from a term I can add this in account-bar.php Just need the required inbuilt Woocommerce codes. Any help is appreciated. Thanks!
To get number of woocommerce published products - $total_products = count( get_posts( array('post_type' => 'product', 'post_status' => 'publish', 'fields' => 'ids', 'posts_per_page' => '-1') ) ); To get attributes count - $total_attribute_terms = get_terms('pa_'. $attribute_slug, array('hide_empty' => false, 'fields' => 'count') ); The `$attribute_slug` can be found on Attribute edit page - Wp admin -> Products -> Attributes -> click on fly-out menu `edit` (not name)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins" }
multiple language website navigation menu suggestion I have completed a single page wordpress theme. I have to add the feature of multiple languages to it. So what I have decided is to make the user create a page such as about-gr Which gr stands for Germany. The website has a navigation menu, which loads the content of the page via ajax. in my jqueyr ajax call, if they selected germany as the language i append -gr to the link and load the page about-gr. it works fine. But the issue is how can I change the language of the menu. * _Should the user create multiple menus for each language and load the relevant menu? I find this difficult to handle for the user. Is there any other way of changing the language of the menu? *_
> Should the user create multiple menus for each language and load the relevant menu? Yes Obviously menus are part of the content of the site, and no one else except for the site owner can decide what will be the content. > I find this difficult to handle for the user. Is there any other way of changing the language of the menu? Sure, localization is hard. You can use the google translate API to translate automatically. IMO this approach is not recommended to any site that don't want to be ridiculed (google translate is good enough to give a general meaning of phrases, but from time to time it will give you a funny translation that is out of context). side note: you are reinventing the wheel. This kind of localizations is usually solved by using dedicated plugins like WPML or by setting different sites (maybe over a network installation) per each language.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, theme development" }
How to get the real file type for images that do not have an extension So i have a front end form that let users upload images from an URL... Everything its ok when the image URL have the proper extension like this: < but when the image url doesn't have an extension like this : < My code doesn't work. This is how i get the extension: $filetype = wp_check_filetype($imageurl, null); Now, if the file name of the image retrieved does have an extension, say jpg, then the output of the above call is Array ( [ext] => jpg [type] => image/jpeg ) However if the extension is not part of the file name then the call above returns the following array Array ( [ext] => [type] => ) How can i get the real file type for images that do not have an extension?
I think, you can not exactly determine, but you can assume one with header data. $headers = wp_get_http_headers( $url ); $mime_type = $headers['content-type']; $ext = ''; foreach ( wp_get_mime_types() as $exts => $mime ) { if ( $mime == $mime_type ) { $ext = $exts; break; } } Now in the `$ext` variable, it could be multiple extensions that have been matched, and there's no way to determine which one the image actually have. But, you could try the first one. if( $ext ){ $exts = explode('|', $ext); $ext = $exts[0]; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images, uploads" }
jQuery Live Form Validation in Wordpress I'm trying to implement the form validation that can be found at: < I can get the demo above working, but when I implement it on my wordpress site no validation occurs. The page where it's implemented is here: < You'll see that the neccesary scripts are included: 1. jquery.validate.js?ver=3.8 2. jquery.js?ver=1.10.2 3. form-validation.css?ver=3.8 as well as the necessary code in the head: jQuery(function(){ jQuery("#firstname").validate({ expression: "if (VAL.match(/^[A-Za-z '-]{3,20}$/) && VAL) return true; else return false;", message: "Required." }); }); etc.... As far as I can tell, the form itself is all okay. Still no validation.
Your page through javascript errors. Try loading the validation scripts on footer (before closing `</body>` tag) rather than within header (within `<head>` tag). If that doesn't work, then try editing the `jquery.validate.js` file, and replace the first line `(function(jQuery){` with `(function($){`. It should work.
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "jquery, forms, validation" }
How do I use Mac Keyboard Icons in WordPress This is a dumb question all right, but everytime I search for the answer I'm just getting results for keyboard shortcuts to control wordpress. In my blog I need to include the images for key combinations for a mac keyboard. How can I do this? If there's a plugin, it'd be really nice to show the keystroke combinations as little key icons - if it supports windows icons to then even better! Thanks in advance!
The answer is rather simple – you type them. :) When properly configured WP should be able to support Unicode characters for `⌘` and `⌥`. Even when not you can fall back to numeric character references (`&#8984;` and `&#8997;` respectively). Windows key has no Unicode symbol and is typically abbreviated as `Win`. `<kbd>` HTML element is appropriate to use for keyboard commands and is often already styled in theme (if it is thorough enough).
stackexchange-wordpress
{ "answer_score": 3, "question_score": -1, "tags": "visual editor" }
is_page not working when loading javascript with add_action in functions.php This code is working in my functions.php and it's loaded properly: add_action('wp_enqueue_scripts', 'js_custom', 50); function js_custom() { wp_register_script( 'js_custom', get_template_directory_uri() . '/js/custom.js', false, null); wp_enqueue_script( 'js_custom' ); } However, this is not working and not loaded: if ( is_page(273) ) { add_action('wp_enqueue_scripts', 'js_custom', 50); function js_custom() { wp_register_script( 'js_custom', get_template_directory_uri() . '/js/custom.js', false, null); wp_enqueue_script( 'js_custom' ); } } Why it's not loaded? I am on the page with the id equal to 273.
I had a similar issue once. I found that running the `add_action` call outside the conditional worked. So try this: function js_custom() { if ( is_page(273) ) { wp_register_script( 'js_custom', get_template_directory_uri() . '/js/custom.js', false, null); wp_enqueue_script( 'js_custom' ); } } add_action('wp_enqueue_scripts', 'js_custom', 50);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "javascript, conditional tags" }
How to 301 all posts I am currently using domain/%postname%/ but I am looking to change it to domain/folder/%postname%/ - I unsure how to 301 all posts. If I was to use something like Redirect 301 /$ domain/folder/$ I am thinking this would probably also redirect all pages, archives etc to the same structure, which I do not want. How can I do this for posts only? Thanks
This Plugin automatically adds a 301 redirection when a post url changes. See also this question on stackoverflow.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "permalinks, redirect" }
how to get the post attachement image in full size? Hi i am using the normal loop to get the post content. Objective is to show images or videos in the blog. I tried `the_content()` for the loop but am getting the thumbnail image i belive, What i want is the original image should be there. Here is the code <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); the_content();//by this am getting the medium sized images from the post content as it is uploaded through add media endwhile; endif; ?> Now i want to show full size of the image for each post. How to do it. can anybody help?
Since you say that your image is "uploaded through add media", you need to select the full sized image when you attach it to the post, not when you try to display it. You should even see in the markup that a smaller size has been chosen (by you). Look over on the right side in the sidebar toward the bottom. You should see a dropdown that will let you choose "size".
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "theme development, loop, themes" }
has_shortcode() - how to detect nested shortcode I'm using `has_shortcode()` to detect a shortcode, it works but not at all. If I put this specified shortcode inside another one the `has_shortcode()` function stops working. has_shortcode( $post->post_content, 'slider' ) For example: [2col] //left column [slider] [2col_next] //right column [slider] [/2col] The `has_shortcode()` function won't work in that case but if I use `[slider]` shortcode without `[2col]` it works perfect. This refers to every shortcode. I'm pretty sure that there's nothing wrong with my shortcodes.
$page_id = get_queried_object_id(); $page_object = get_page( $page_id ); if ( strpos($page_object->post_content, '[/slider]') )
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "php, shortcode" }
Conditional Tags If Custom Post Parent & Child? Check on the single-artists.php whether we are viewing the parent or child of the said custom post? Tried this but always shows the top child content, rather then showing the two different area <?php if ('artists' == get_post_type() || $post->post_parent=='artists') { ?> the child single-artists.php <?php } else { ?> the parent single-artists.php <?php } ?>
post_parent is a numerical value field in $post object. So you should check if there's a valid number. Try this - <?php if ( $post->post_parent > 0 ) { ?> the child single-artists.php <?php } else { ?> the parent single-artists.php <?php } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, conditional tags, single" }
How do I change the default WordPress e-mail ID for sent e-mail? I have created a blog website at `careerdemo.com` and installed WordPress to run it. When a person signs up, they get an email from the address `[email protected]` (this is, I guess, a default setting in WordPress). I want to change that, so that e-mails come from my own address,`[email protected]`. (So any new user will get e-mails from my own e-mail address, `[email protected]`.) How do I customize my FROM e-mail address?
Add the following to your functions.php: add_filter('wp_mail_from', 'new_mail_from'); add_filter('wp_mail_from_name', 'new_mail_from_name'); function new_mail_from($old) { return 'your email address'; } function new_mail_from_name($old) { return 'your name or your website'; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "plugins" }
How to use WordPress 3.8 back-end CSS in front-end? How to use WordPress 3.8 back-end CSS in front-end? I want to use the back-end button CSS, button icons CSS etc. onto the front-end side. Is there any way, I can just call the CSS class in front-end to use them directly?
I believe you're asking how to include the admin styles in your front end theme? If so, you simply need to either enqueue 'wp-admin' on it's own or list it as a dependency for your theme/plugin stylesheet. Here are examples of both methods: By itself: wp_enqueue_style( 'wp-admin' ); As a dependency: wp_enqueue_style( 'my-theme-styles', 'path-to-my-css.css', array( 'wp-admin' ), '1.0.0' ); There are also several individual parts of the admin css that can be enqueued separately as well: 'dashicons' 'admin-bar' 'thickbox' 'wp-admin' 'buttons' 'colors' Although enqueueing any of these individually may have less than ideal results as I don't believe they are listed as dependent on eachother.
stackexchange-wordpress
{ "answer_score": 3, "question_score": -3, "tags": "css, front end" }
how to design change in woocommerce cart page and all other page also by theme? I want to change all woocommerce pages design change as per my theme template so what can i do .
Yes its possible. To override WooCommerce template files in your theme (or child theme) simply make a folder named `woocommerce` within your theme directory, and then create the folders/template file you wish to override within it. This link **overriding templates** is having the procedure to override templates via a theme.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, theme development, themes" }
How to include a file only on dashboard widgets page? I want to add some styles to the widgets input fields. Therefore I want to include a style.css file only on the `wp-admin/widgets.php` page. How can I detect the above page and include file there?
You can use the following code. Asuming that the css file `style.css` is inside the css folder of your theme: function wpse_126614_enque( $hook ) { if ( 'widgets.php' != $hook ) { return; } $template_url = get_template_directory_uri(); wp_enqueue_style( 'admin-style-widget', $template_url . '/css/style.css' ); } add_action( 'admin_enqueue_scripts', 'wpse_126614_enque' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, widgets, admin, wp enqueue style" }
WordPress 3.8 Backend Admin Color Scheme add more scheme how to do? How can I add additional admin color schemes into Wordpress 3.8? I want to add two more with a yellow shade and a green shade.
I would like to recommend you to learn Admin Color Schemes plugin which provides 8 new color schemes. You need to install Grunt.js and SASS compiler. More information you can find during investigation the plugin stuff. Use it as a copy to create your own plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, themes" }
How to Customize "WordPress > Error" Text in Titlebar? When a user doesn't enter all required things in comment box area and click on submit comment button, a new page is shown telling user that some required fields are missing such as name, email, etc. The page contains `"WordPress > Error"` text in titlebar. I want to replace this text with my custom text. I have been doing this by manually replacing following line in `wp-includes\functions.php` file: $title = $have_gettext ? __('WordPress › Error') : 'WordPress › Error'; Now I don’t want to edit core file. I want to know if it is possible to do the same thing by using my blog theme's `functions.php` file?
Changing interface string is often done using `gettext` translation filter, but I was in the mood for something different so creatively mangled die handler to achieve it: add_filter( 'wp_die_handler', function () { if ( false !== strpos( $_SERVER['SCRIPT_NAME'], 'wp-comments-post.php' ) ) { return function ( $message, $title, $args ) { _default_wp_die_handler( $message, 'Our Custom Title', $args ); }; } return '_default_wp_die_handler'; } );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "title" }
Multisite wordpress and subdomain URL collisions I have a multisite WordPress installed on a server using a domain, **site.com** and I have a subdomain setup in WordPress, so subsites are at **sub1.site.com** , **sub2.site.com** etc. In addition to this, the main site has other services in subfolders that are not related to WordPress, such as `site.com/something`. Everything is working fine, except that when a customer on a subsite uses permalinks by post name, and uses the same title as one of the main site's subfolders, it goes to the main site's subfolder; for example `sub1.site.com/something` goes to the same place as `site.com/something`. Is there anything I can do _(by editing`.htaccess` or `httpd.conf`_? Or should I just move WordPress to it's on subfolder in main site (`site.com/wordpress`) to prevent these URL collisions?
You could just prevent slugs matching existing directories. There are two filters for that. Example, not tested: add_filter( 'wp_unique_post_slug_is_bad_hierarchical_slug', 'prevent_directory_slugs', 10, 2 ); add_filter( 'wp_unique_post_slug_is_bad_flat_slug', 'prevent_directory_slugs', 10, 2 ); function prevent_directory_slugs( $bool, $slug ) { return is_dir( ABSPATH . '/' . $slug ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "multisite, permalinks, url rewriting, htaccess, subdomains" }
Youtube shortcode I'm trying to make this shortcode work but without any success. All attempts gives me a white square. function youtube($atts) { extract(shortcode_atts(array( "value" => ' "width" => '475', "height" => '350', "name"=> 'movie', "allowFullScreen" => 'true', "allowScriptAccess"=>'always', ), $atts)); return '<object style="height: '.$height.'px; width: '.$width.'px"><param name="'.$name.'" value="'.$value.'"><param name="allowFullScreen" value="'.$allowFullScreen.'"></param><param name="allowScriptAccess" value="'.$allowScriptAccess.'"></param><embed src="'.$value.'" type="application/x-shockwave-flash" allowfullscreen="'.$allowFullScreen.'" allowScriptAccess="'.$allowScriptAccess.'" width="'.$width.'" height="'.$height.'"></embed></object>'; } add_shortcode("youtube", "youtube");
Few remarks about your code: **1)** First you should use something like: < instead of the YouTube page: < in your embed code. **2)** You can always use the `[embed]` shortcode if you need to embed YouTube videos: [embed width="600" height="400"] **3)** You should consider adding a _prefix_ to your shortcode callback, for example `macko_tarana_` to avoid function name collision with other plugins. **4)** Try to avoid `extract(...`, use `$atts = shortcode_atts(...` instead. **5)** Consider atting the third parameter to `shortcode_atts`, i.e. the shortcode name so you can use the `shortcode_atts_{$shortcode}` filter. More about it here in the Codex. **6)** Always **escape** the input attributes, for example with `esc_attr()` or `esc_url()`. Hope this helps.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "shortcode" }
3.8 Media Upload and Custom Meta Box I've been using Tammy Hart's Reusable Custom MetaBox code for some time now but with the recent 3.8 update the media upload seems to be no longer functioning, and the code is no longer supported. The console is highlighting this area as being `Uncaught TypeError: Object #<Object> has no method 'media'`. Which I assume has something to do with a change in how 3.8 handles the media uploader. Reusable-Custom-WordPress-Meta-Boxes/metaboxes/js/scripts.js imageFrame = wp.media({ title: 'Choose Image', multiple: false, library: { type: 'image'}, button: { text: 'Use This Image' } });
I'm an idiot. The reason the media uploader was not working, was because the post type I was using this on only had the title field set up in post type support. As such wp_enqueue_media() was not included as it normally would have been if the editor was included in post type supports. To fix this I added wp_enqueue_media(); to my cpt registration function.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, media library, media modal" }
Add logo in navigation bar before menu items in twenty thirteen? I am customizing the twenty thirteen theme and want to add a logo image in the navigation bar before menu items like this link. I have tried different approaches but didn't work. Would appreciate any suggestions in this regard.
Tested on a Twenty Thirteen & Twenty Twelve child theme. !enter image description here Try this from your child themes functions.php file. You can add the image using various methods. add_filter( 'wp_nav_menu_items', 'wpsites_add_logo_nav_menu', 10, 2 ); function wpsites_add_logo_nav_menu( $menu, stdClass $args ){ if ( 'primary' != $args->theme_location ) return $menu; $menu .= '<nav class="nav-image"><img src="' . get_stylesheet_directory_uri() . '/images/header.png" /></nav>'; return $menu; } Sample CSS for your child themes style.css file: .nav-logo { float: left; margin-right: 20px; } You'd also want some Media Queries which will vary per theme. Here's the result on Twenty Twelve: !enter image description here
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme twenty thirteen" }
How to hide a custom field from admin? I created a custom field that I would like to hide from the wp-admin (because the system generates it and I don't want user to change it; Hidding it with CSS should be OK in this case), Like this, 'postal_address' => array( 'guid' => 'postal_address', 'control' => array( 'type' => 'text', 'default' => '', 'allow_empty' => false ), 'label' => 'Postal Address', 'help' => 'Postal Address of Apartment' ), Wich works, Problem is that the html element doesn't have any id/class so I can select it and Hide it, Is there a way to add an html attribute from the definition? thanks!
If you're automatically populating a custom field, you can put an underscore at the beginning of the name ("_postal_address") to hide it in the admin UI.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom field, customization" }
Count number of post in Taxonomy? wp_count_terms() counts the number of terms in a taxonomy but not the number of post that have those terms and I've found that wp_count_post() does not accept a taxonomy. So whats a guy gotta do to count the number of post in a taxonomy term? Example: Term: Apples Post: 89 (this is what I want to get, the number of post with the 'Apples' taxonomy) Thanks!
The function you are looking for is get_term() < and the code would look something like this: $term = get_term( 1, 'category' );//for example uncategorized category echo 'count: '. $term->count;
stackexchange-wordpress
{ "answer_score": 9, "question_score": 2, "tags": "custom taxonomy, count" }
get unserialized array without using get_option() I'm working on a WPMU plugin that cycles through tables in each blog on the network. I can't use get_option to pull the settings array out of the `wp_n_options` tables, so I'm trying to do it by querying $wpdb and then using `unserialize()`. I know the query is successful because I can `print_r` `result`, but it's wrapped in an array, and I can't figure out how to just get the serialized string out of it. Any pointers? \---EDIT--- What it's actually returning is this: `stdClass Object ( [option_value] => ~serialized string~ )`
You can use the following two inbuilt functions to do this. 1. **switch_to_blog** 2. **get_option** You can use both in the following way to make a function out of it which would give you the option. Put the below in the **`functions.php`** file function wpse_get_options( $blog_id = 1 ){ switch_to_blog( $blog_id ); $get_option = get_option( $option ); // Replace $option with the option name restore_current_blog(); // Switch back to the original blog return $get_option; } Now you can use the above function to fetch the options by using the function and passing the blog id/ sub site id. $options = wpse_get_options( $blog_id ); // Replace the $blog_id with blog id of your sub sites.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wpdb, options" }
Related posts popup I want to retain visitors on my blog by showing them other posts related to the post they are reading. But it seems they don't see this widget at all. So I have an idea to show this list in a popup (DIV) which appears in the bottom (or any side) of the page after the user scrolls the post for some extent. Does anybody know the best way to do this?
I've found exactly what I was looking for: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, posts" }
How to hide the year in archive link I am using the following code to show the archive link by month. <?php wp_get_archives('type=monthly&limit='.date('m').'&show_post_count=1'); ?> but it shows as * december 2013 (3) * november 2013 (2) but i need to just months only as.. * december (3) * november (2) how can I do that in some easy steps?
You could use a regexp to remove the year, though it's a little hacky: $string = wp_get_archives('type=monthly&limit=20&echo=0'); $pattern = ' ((19|20)\d{2}(</a>))'; echo preg_replace($pattern, '\\3', $string); Answer from this stackoverflow question: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "archives, date" }
Content area is too small I want to change to the new twenty fourteen theme because it's a nice look and feel. However if I try so the content is reduced only on a small area and a lot of space on the page is unused. I already tried this: how to create a conditional content_width for a wordpress theme? but it does not help me at all. to give you an image of what i mean look at this: Unused pagearea marked in yellow Some of you know where and what do I have to change to fit the whole area? My blog: www.sysstem.at
You need to edit your theme's CSS to do this. In style.css in your 2014 folder on line 1021: .site-content .entry-header, .site-content .entry-content, .site-content .entry-summary, .site-content .entry-meta, .page-content { margin: 0 auto; max-width: 474px; } change 474px to whatever you want your content width to go up to. Or set it to 100% to stay full width.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post content" }
Should I put my plugin javascript inline? I have a small bit of (localised) Javascript bundled with a plugin. Currently it's in a non-minified .js file, called at via enqueue_scripts. Given that this script will likely run on every page, should I minify it or output it so it's inline in the page?
If you minify it you'll be able to reap the advantage of caching the file. If you inline it, the browser will have to download the script every time it accesses a page with your plugin on it. I'd minify it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, javascript" }
How to display recent posts added in custom post types I have tried a code posted here>>Custom Post Type: Get most recent permalink But the thing is-it is showing only one post from the recent and without get_the_title,,, can anyone help me to achieve, upto 10 posts' Title and permalink of custom post type. I am googling from about 1 hour.. Please anyone help me
The answer is essentially in Codex! <h2>Recent Posts</h2> <ul> <?php $recent_posts = wp_get_recent_posts(array('post_type'=>'book')); foreach( $recent_posts as $recent ){ echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> '; } ?> </ul> The only thing I did was add an argument to search for the `book` post type instead of the default `post` type. And this is probably a duplicate of this question anyway, but the system won't let me mark it as such.
stackexchange-wordpress
{ "answer_score": 12, "question_score": 0, "tags": "custom post types, custom taxonomy" }
get_template_part() to render single page Theme I´m developing a single page theme and want to render all pages with their respective templates on a single page. I know I could make a query and write the markup for the respective page, but I prefer separate all templates in files. What I want is to make the loop and load the template-*.php file for each page. Is that possible? To clarify this a little bit, below follows an example of what I want: $query = new WP_Query(); $wp_query->query('post_type=page'); while ($wp_query->have_posts()) : $wp_query->the_post(); get_template_part('templates', 'template_slug'); endwhile; and in the while loop output not only the content, but the content in teh right markup. Any help is more than appreciated!
Something like this if you want to call mytemplate.php: get_template_part( 'template'); Or something like this if you want to call content-mytemplate.php: get_template_part( 'content', 'mytemplate' ); I hope that this will help you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, pages, page template, get template part" }
How to display data from db in select list I wonder what it's wrong in my code. I can't get all of data in column "adres". In result I only have the lest record. Thanks for help. global $wpdb; $result = $wpdb->get_results ("SELECT adres FROM wp_ow_adres;"); foreach ( $result as $result ) echo '<td><select id="adres" type="text" name="adres"> <option value="">Select your address</option> <option>'.$result->adres.'</option> </select></td>';
You're recreating the select element on every iteration through the loop, and you need to name your current loop assignment variable differently, as you're overwriting your original. Lastly, you're also not assigning a value to the options within the loop, so you're not going to get anything on the form submission, and text isn't a valid type for a select element. Try this: global $wpdb; $results = $wpdb->get_results ("SELECT adres FROM wp_ow_adres;"); echo '<td><select id="adres" name="adres">'; echo '<option value="">Select your address</option>'; foreach ( $results as $result ) { echo '<option>'.$result->adres.'</option>'; } echo </select></td>'; FYI, this is technically off topic for this site as it's a php issue rather than a WordPress one, it just happens in the "context" of WordPress.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database, query, sql" }
Is this plugin being loaded before file.php, subsequently not allowing me to use certain functions? I'm trying to use `get_home_path()` in my plugin, however, I get a _`call to undefined function`_ fatal error (running Wordpress 3.8). I believe this would imply that my plugin is being loaded before _wp-admin/includes/file.php_ where `get_home_path()` is located, right? Is it just me, or is that a little odd? How can I make file.php load first so I can access this function? The line of code that causes this issue (within my plugin) is: register_theme_directory(get_home_path().'/material/views');
to make sure everything required is loaded before plugins loads, use plugins_loaded hook and initialize your plugins its callback funtion. for example: add_action('plugins_loaded',function(){ // initialize your plugins here. });
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugins, plugin development, core" }
WP 3.8 theme customizer error I'm trying to make some customizer for my theme, but i've got JS error "Uncaught ReferenceError: wp is not defined " LOL. I wrote all code based on Codex, maybe it is just WP 3.8 bug? Or what i'm doing wrong? my code - PHP: add_action( 'customize_preview_init', 'customizer_preview' ); function customizer_preview() { wp_register_script( 'wproto-customizer-preview', get_template_directory_uri() . '/js/admin/screen-customizer.js', '', true ); wp_enqueue_script( 'wproto-customizer-preview', array( 'jquery', 'customize-preview' ) ); } JS: ( function( $ ) { // here i've got an error "wp is not defined" wp.customize( 'blogname', function( value ) { value.bind( function( newval ) { $( '#text-logo .site-title' ).html( newval ); } ); } ); } )( jQuery ); please help :)
I think your way of enqueueing is wrong here. When you use `wp_register_script`, you only need to pass the handle to `wp_enqueue_script`. Try updating your function to: function customizer_preview() { wp_enqueue_script( 'wproto-customizer-preview', get_template_directory_uri() . '/js/admin/screen-customizer.js', array( 'jquery', 'customize-preview' ) ); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme customizer" }
post_status => publish not working I have a front end form that let users submit a post. This is how i store the data when a post is submitted : if ( isset( $_POST['submitted'] )) { $post_information = array( 'post_title' => wp_strip_all_tags( $_POST['postTitle'] ), 'post_content' => $_POST['postContent'], 'post_type' => 'post', 'post_status' => 'publish' ); $new_post = wp_insert_post( $post_information ); The post is not showing in my post page unless i go through my dashboard and click over The UPDATE button. THIS IS HOW I QUERY MY POSTS : $args = array( 'posts_per_page' => 5, 'paged' => $paged, 'meta_query' => array( array( 'key' => '_wti_like_count','value' => 5, 'compare' => '<=','type' => 'numeric') ) ); query_posts( $args ); How can i make my submitted posts publish automatically?
The post gets added and published but since you have the meta query and the meta key is not added when you submit the post from frontend, it does not show up. Use the following code which adds the meta data as needed. if ( isset( $_POST['submitted'] ) ) { $post_information = array( 'post_title' => wp_strip_all_tags( $_POST['postTitle'] ), 'post_content' => $_POST['postContent'], 'post_type' => 'post', 'post_status' => 'publish' ); $new_post = wp_insert_post( $post_information ); // Add the post meta add_post_meta( $new_post, '_wti_like_count', 0, true ); add_post_meta( $new_post, '_wti_unlike_count', 0, true ); add_post_meta( $new_post, '_wti_total_count', 0, true ); }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "query posts, wp insert post, save post, publish, wp update post" }
how to add a facebook page latest posts into my wordpress site hi I want to show all the posts of a face-book page in my word press site. I tried "Embedded posts"..but when I give the URL of post it shows the preview as "This Facebook post is no longer available. It may have been removed or the privacy settings of the post may have changed." what should I do for this? any alternative idea? the code i got for embedded post is: <div id="fb-root"></div> <script>(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1& appId=231268450376260"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));</script> <div class="fb-post" data-href=" data-width="500"></div>
Please paste here all your code about this function. And next take a look at this tutorial: < Best regards!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, facebook" }
Appearance > Menus > Left Sidebar > Add Toggle How can i add my own toggle here ? There are toggles for each post type but I would like to add this without creating a new post type. Where should I start looking ? !enter image description here Let say I wish to add something like this:!enter image description here It will work the same as link with URL = # and it will look more clear for some people
You custom box can be added with adding meta box on nav menu page. So - function Register_My_Nav_Menu_Metaboxes(){ add_meta_box( $id, $title, $callback, 'nav-menus', 'side' ); } add_action('load-nav-menu.php', 'Register_My_Nav_Menu_Metaboxes'); I hope you know how to add the metabox $id, $title, $callback and utilize it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
Get post by ASC from custome field DATE picker i want to custome post by ASC. i have some add some post in bachend one of the field date picker. i want to post by date which i set in date picker field <?php $args = array( 'post_type'=>'upcoming_events', 'order' => 'ASC', ); global $more; query_posts( $args ); while (have_posts()) : the_post(); ?> **Ex.** some post which i set date(datepicker cusomefiled) and title output is below **DATE(datepicker)** **title** 19-12-2013 London 29-12-2013 Spain 15-01-2014 Paris **i want to** **DATE(datepicker)** **title** 15-01-2014 Paris 19-12-2013 London 29-12-2013 Spain
So what you need to do is order it by the custom value of the meta_key date value. Something like this (untested): $wp_query = new WP_Query( array( 'post_type' => 'upcoming_events', 'order' => 'ASC', 'meta_query' => array ( array ( 'key' => 'your_custom_date_key', 'value' => date('Y-m-d') ) ), 'orderby' => 'meta_value' ) ); Hope that helps.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, mysql, advanced custom fields" }
date.php shows only three posts' title. how to fix it? my `archive.php` <?php wp_get_archives( array( 'type' => 'monthly', 'limit' => 12, 'show_post_count' => 1 ) ); ?><br/> my `date.php` <?php get_header(); while (have_posts()) : the_post(); echo the_title() . '<br/><br/>'; endwhile; wp_reset_query(); get_footer();?> when I click **december 2013** form **myblog.com/archive** then it's goes to **myblog.com/2013/12** and showing **only three posts' title** from the december 2013. how can I fix it to show all the post from the particular month?
Use the `pre_get_posts` action to modify number of posts per page on date archives. This would go in your theme's `functions.php` file: function wpa_date_posts_per_page( $query ) { if ( !is_admin() && $query->is_date() && $query->is_main_query() ) { $query->set( 'posts_per_page', -1 ); } } add_action( 'pre_get_posts', 'wpa_date_posts_per_page' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "archives, date" }
Setting a new default template for the creation of a page Right off the bat I would like to say that I am a WordPress noobie, so I'm really sorry if I infuriate you. I've recently taken over the management of a clients website an have been sent a request to change the pre-selected "Default Layout" template to one we have created our self. The client has recently hired new staff to create new page for them, and they keep forgetting to change the layout from Default to the custom template, I have been asked to make sure that our template is selected when the page loads so we can minimize mess-ups on their end. I've spent about 3 hours looking for a solution, can any one suggest a way to do this or something similar?
The page template you are looking to overwrite is the `page.php` file. If you replace the code in that file with the code from your template (or delete it and rename your file to `page.php`), your problem should be taken care of.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, pages, page template, theme options" }
Help with changing style of the extended menu drop down I am trying to change the style of the extended menu drop down from being on the right side to the left side. As you can see by the picture provided, the menu item named "Catholic Women's league of Canada" comes down on the right side. The reason why I want to change it to the left side is because under my "Contact" menu item there are two sub items similar to the "Parish Committees" menu item and the menu travels off of the screen. Any ideas of where I can look in the style.css file to find where I can change the way these menu items drop down? !Menu item display Thank you!
There should be something like this in the CSS: .menu ul ul ul { left: XXpx; } Try changing that to .menu ul ul ul { right: XXpx; } But nothing can be said for sure without seeing the CSS first.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, css" }
Assign SQL 'post_thumbnail' column as featured image I have added a column called `post_thumbnail` to my wp_posts table. Is there any way I can make `post_thumbnail` to each post's featured image?
How is the post_thumbnail information stored? If you've already created an attachment with the image and are storing the attachment's `postId` in `post_thumbnail`, then you just need to go through your posts and update the meta using `update_post_meta($postId, '_thubmnail_id', $attachmentPostId)`. If `post_thumbnail` stores the path to an image file on your server, you need to create an attachment using wp_insert_attachment and pass in that file location. If the files are not already stored in the uploads directory, you can use the Add From Server plugin to import the files into wordpress as attachments. You can then use `update_post_meta` to set the attachment as your featured image. If `post_thumbnail` stories the URI of the image, you need to save it to your server, then create the attachment, then update the post's meta.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails" }
Recommended Media Size for Twenty Fourteen is there a recommended media size for Thumbnail size in twenty fourteen? am trying to sort out my website so that it doesn't serve any resized media on the home page, most of the resized media are coming from the featured image on the home page. When i test the page speed i get "The following images are resized in HTML or CSS" Any help on the thumbnail media size wold be greatly appreciated.
Twenty Fourteen uses 2 custom media sizes: * 672x372px for post thumbnail image size * and 1038x576px for 'twentyfourteen-full-width' custom image size So for images uploaded _after_ the theme is activated, these 2 size are created automatically, but for images uploaded _before_ twentyfourteen is activated, an available size is used and image is resized via html/css properties. What I suggest is for new images upload files having width >= 1038 px and height >= 576 px and let theme resize them. For images already uploaded a plugin like Regenerate Thumbnails can be very usefull (but images must be larger than custom size required by theme or the thumbnail will not be generated).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "themes, post thumbnails, media settings" }
wp_head hook content showing up at top of RSS feed The RSS feed for a site I maintain recently stopped working. I did a little investigating and found that the `wp_head` hook contents of several plugins is getting injected at the top of the page, causing an XML parse error (obviously). I'm really not sure what the problem is. I'm not really familiar with how WordPress generates its feeds, so I don't have much insight there. I recently upgraded the blog to 3.8, but the upgrade was done yesterday, and the guy who brought the issue to my attention made it sound like it had been going on for longer. I don't know for sure though, it certainly could be a 3.8 bug. I've tried different themes, tried disabling plugins. When every plugin is disabled, the feed works, because nothing is hooking onto the `wp_head` hook that's causing the problem.
The wp_head hook is not normally called for feed generation, so you need to find which plugin or other piece of code is adding that to the feed. Also check that your WordPress core files have not been altered somehow.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rss, feed, wp head" }
Querying multiple meta_keys in Wordpress SQL query Here's my Query... I'm looking to narrow this query down to users of one specific role ("meta_key = 'wp_capabilities' AND meta_value = 'employee'")...how do I add that additional conditional to this string? $get_users = "SELECT * FROM $wpdb->users WHERE ID = ANY ( SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$meta_key' AND meta_value LIKE '%$search%' ) ORDER BY user_nicename ASC LIMIT 10000"; Thanks in advance...
WordPress Provides a native functions to query these kind of things very easily like WP_User_Query $args = array( 'meta_query' => array( 'relation' => 'AND', array( 'key' => $meta_key1, 'value' => $search1, 'compare' => 'LIKE' ), array( 'key' => $meta_key2, 'value' => $search2, 'compare' => '=' ) ) ); $user_query = new WP_User_Query( $args );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, database, wpdb, sql" }
Get Value of Custom Field I use a dropdownbox to show all custom types ('abschreibungstabelle'). It works fine. But now, I want to show the value of the custom field 'nutzungsdauer' in my input-field. Any ideas? <input type="text" class="text-input" placeholder="Nutzungsdauer" value="" name="nutzungsdauer" id="nd"> function.php function afa_type_dropdown( $post_type ) { $posts = get_posts( array( 'post_type' => $post_type, 'numberposts' => -1 ) ); if( ! $posts ) return; $out = '<select id="afa_select"><option>Anlagegut auswählen</option>'; foreach( $posts as $p ) { $out .= '<option value="' . get_permalink( $p ) . '">' . esc_html( $p->post_title ) . '</option>'; } $out .= '</select>'; return $out; }
As the `$posts` are the posts of post_type `abschreibungstabelle`, you can get the custom field values by using **`get_post_custom_values`** if( ! $posts ) return; $out = '<select id="afa_select"><option>Anlagegut auswählen</option>'; foreach( $posts as $p ) { $custom_field_value = get_post_custom_values( 'nutzungsdauer', $p->ID ); // Now you can use the value the way you want $out .= '<option value="' . get_permalink( $p->ID ) . '">' . esc_html( $p->post_title ) . '</option>'; } $out .= '</select>'; return $out; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, customization" }
Instantiate class to be available to all plugin functions I'm developing a plugin for a site that has to communicate with several non-wp tables in a database. For that I made a class that contains all of the MySQL-related functions. When you declare a function within a plugin, you can easily call it within a theme. But how to do that with a class? Is there a way to instantiate it with wordpress init and make it available to plugin(s) and theme(s)? Thank you for your time! :)
Ryan McCue had a nice idea for his plugin Hopper: add a callback for a custom filter to return the current instance. Sample code for the plugin: class Plugin_Class { public function __construct() { add_filter( 'get_plugin_class', array ( $this, 'provide_instance' ) ); } function provide_instance() { return $this; } } In a theme or a second plugin you can access the instance now like this: $plugin_class = apply_filters( 'get_plugin_class', NULL ); if ( is_a( $plugin_class, 'Plugin_Class' ) ) { // use the plugin class instance }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, plugin development" }
Text of posts is suddenly not visible anymore (WordPress 3.8 running Twenty Eleven theme.) < I just realized that neither on the Wordpress homepage nor after opening a post I can see any text. If I click on edit though or choose a post from the manager then everything seems alright. Everything is in place, including the title of the posts. Just the text of a post is not visible on the blog. If I remember correctly this issue is no direct result of the latest Wordpress update. I don't even have an idea right now where to look for the reason.
I'd recommend disabling some plugins first, and going from there. It could very well be your `wp-flattr-button` that's causing the issue. In the case, it seemed to be the ShareThis plugin.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "troubleshooting" }