INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to pass arguments to add_action() I declared an action for a single event in Wordpress which accepts an array as an argument: $asins = array(); //I had to declare this since I'm getting a notice of undefined variable if I don't add_action('z_purge_products_cache', array($this, 'purge_products_cache', $asins)); I also tried this one, but it doesn't perform the action either: add_action('z_purge_products_cache', array($this, 'purge_products_cache')); Then I schedule it: wp_schedule_single_event(time() + 20, 'z_purge_products_cache', $asins_r); Then here's the function that will be called once wp cron executes the action: public function purge_products_cache($asins){ //send email here } Any ideas?
The parameter needs to be passed to the callback function in the wp_schedule_single_event function, not the add_action function. Try this: add_action('z_purge_products_cache', array($this, 'purge_products_cache')); Then schedule the event, putting the parameter in an array: wp_schedule_single_event(time() + 20, 'z_purge_products_cache', array($asins_r)); Your `purge_products_cache` function will be called with parameter `$asins_r`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "hooks, actions" }
Img Src File path issue To get images loaded correctly when I use img src in HTML, I have to give the entire file path. Using CSS I would only need to use: `background-image: url(images/morebutton.png)` With img src I have to use this: <img src="wp-content/themes/blankslate/images/morebutton.png"> Using this file path gives me the image on the home page, however when I click through to the article page, the image doesnt load.. I'm having the same issue with my logo, it shows on the homepage, any additional pages it doesnt show. Can anyone tell me if the file path setup I have is incorrect?
No your file path setup is correct, you need to provide the absolute path in you img src for images to load on other pages as relative path would change to, and instead it should be So you should define a constant in your function.php for path to image directory, and then use it in img src. if( !defined('THEME_IMG_PATH')){ define( 'THEME_IMG_PATH', get_stylesheet_directory_uri() . '/images' ); } and then you can use img tag as <img src="<?php echo THEME_IMG_PATH; ?>/morebutton.png" alt=""/> That would solve your issue. You can use the constant anywhere in your theme, handy to use.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "images" }
How can I make the Twitter Tools plugin hyperlink every link? It appears that (Twitter) shortened links are not auto-hyperlinked whilst non-shortened links are. Is there a patch to make all links hyperlinked - therefore clickable? E.g. < <
Never used this plugin. WordPress has a function called `make_clickable()` which might help you. Example: $string = "This is a long text that contains some links like and ."; echo make_clickable($string); Output: This is a long text that contains some links like <a href=" rel="nofollow"> and <a href=" rel="nofollow"> .
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, twitter" }
Issues with Post 2 Post Plugin I am trying to create connections between some of my posts. I have pairs of posts that need to go together (post with a quiz). I found the Post 2 Post plugin, which seems perfect for what I need. I have installed the plugin, but whenever I add the following code to my theme's functions.php file I get a white screen whenever I try to save a page on the admin side (it still saves, but I get a white screen). <?php function my_connection_types() { p2p_register_connection_type( array( 'name' => 'posts_to_quiz', 'from' => 'post', 'to' => 'quiz' ) ); } add_action( 'p2p_init', 'my_connection_types', 100 ); ?> I switched themes and it corrects itself, so I know it is an issue with the theme, but not sure where to start debugging. I am using the Bones framework, but have made some changes (not much to the functions.php file though). Any ideas would be much appreciated.
Your error message is discused at this site: < in short they fixed a bug in the addon: wp-content/plugins/advanced-custom-fields/core/fields/taxonomy.php row/line 419: function start_el( &$output, $term, $depth, $args = array(), $current_object_id = 0) wp-content/plugins/advanced-custom-fields/core/fields/taxonomy.php row/line 442: function end_el( &$output, $term, $depth = 0, $args = array() )
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, posts, customization, themes" }
woocommerce hook publish product I want to add an action whenever the admin publishes a product, but the WP hook publish_post does not trigger then - even though a wc product is just another type of post. I haven't found a woocommerce hook that triggers when a product is published. Any thoughts?
I recommand you to use the `transition_post_status`. See example below : add_action('transition_post_status', 'wpse_110037_new_posts', 10, 3); function wpse_110037_new_posts($new_status, $old_status, $post) { if( $old_status != 'publish' && $new_status == 'publish' && !empty($post->ID) && in_array( $post->post_type, array( 'product') ) ) { //add some cde here } } This hook is really handy. It allows you to target a specific action: every time post data is saved. But with code I add you can avoid trigger your code if it's a draft save or an updtate.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugins" }
Custom post content to display in a normal post? Is it possible to display custom post content in a normal Wordpress post? For example I have created a custom post type called Games Database, it is populated with game boxart, title, genre, platform, publisher, developer, review score and release date. Now when I create a new (normal) wordpress post I want to be able to select a game from a drop down menu that the post relates to, for instance if I'm writing a post about Mario Galaxy 2 I would want to select that game from my database and then when I view the post on the website I want to be able to see a widget display with all of the games details. Is it possible to do this?
### Solution #1 - home brew You could * add a metabox using `add_meta_box()` Example on the bottom of that link. * In your MetaBox callback you could add a Query like this one, but for posts * Then use the jQuery UI Autocomplete plugin that is shipped with WordPress like explained in that answer. ### Solution #2 - from the super market But you could as well use "Posts2Posts" which can be found * in the official repo on wp.org * or on GitHub where you'll find extensive tutorials in the Wiki and help in the questions/issues list.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types" }
Display custom post function ONLY if it has a value How do I get the following code to insert a link only if the custom function has a value? <td><a href="<?php echo esc_html( get_post_meta( get_the_ID(), 'game_review_link', true ) ); ?>"><div class="rating-<?php echo esc_html( get_post_meta( get_the_ID(), 'game_rating', true ) ); ?>"><?php echo esc_html( get_post_meta( get_the_ID(), 'game_rating', true ) ); ?></div></a></td> Basically I'm trying to link a review score to a review but if a review hasn't been written I don't want a link to appear. Thanks in advance.
<td> <?php $review_link = get_post_meta( get_the_ID(), 'game_review_link', true ); if ( ! empty( $review_link ) ) : ?> <a href="<?php echo esc_html( $review_link ); ?>"> <div class="rating-<?php echo esc_html( $review_link ); ?>"> <?php echo esc_html( $review_link ); ?> </div> </a> <?php endif; ?> </td> **UPDATE** Thanks to Chip Bennet, this is now working code. Changed isset conditional check to ! empty.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types" }
Getting error of unexpected output during activation I have seen one plugin named lordlinus business hours When I am trying to install it, I am getting error : > The plugin generated 2 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin. How can I resolve this error?
You have the same username as the plugin author? o.O The error comes from line 444: There's two characters between `?>` and the next `<?php` Change: add_action( 'admin_menu','business_hours_menu' ); ?> <?php add_action( 'widgets_init', 'lordlinus_businesshour_load' ); To: add_action( 'admin_menu','business_hours_menu' ); add_action( 'widgets_init', 'lordlinus_businesshour_load' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, errors" }
Which part of the plugin to change so the updater won't register the next version? I have made a change in WP qTip plugin so only a specific `a.something[title]` instead of `a[title]` is affected. It's just a small plugin, but if there is a new version and my client wll update this plugin the changes will be lost. My question is what in the plugin should I change so the update will be not possible and plugin not recognized? Will be changing the name enough? E.g. from: `Plugin Name: WP jQuery qTip` to som thing like: `Plugin Name: WP jQuery qTip - No Update` ? Or I need to make additional changes in the plugin too?
You should not modify Themes or Plugins that you don't control. Instead, use one of two options: 1. Patch the Theme/Plugin, and submit the patch to the developer 2. Fork the Theme/Plugin It sounds like you've opted for option #2. In that case, I would recommend changing both of the following: 1. Update the entire header phpDoc refs to your forked version of the Plugin 2. Change the directory name from `/wp-content/plugins/{plugin-name}`, to `/wp-content/plugins/{forked-plugin-name}` I believe the bare-minimum change needed is changing the `Plugin name` phpDoc, and the Plugin's directory name.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, updates" }
Change post date for testing purposes Is there a way I can change a post date to preferably a different month and a year for testing purposes?
You can do this from the dashboard, enter the post and on the right hand side you can edit the published date.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "date, testing" }
How use %like% in sql statement wordpress i use a **like** %text% statement in wordpress: SELECT * FROM location WHERE name LIKE "%on" OR name LIKE "%on%" i tried anything but it's not run: $wpdb->get_results($wpdb -> prepare("SELECT * FROM location WHERE name LIKE %1s OR name LIKE %2s", '%'.like_escape('on'), '%'.like_escape('on').'%'), ARRAY_A); please help me
`$wpdb->prepare()` doesn't actually fully support `sprintf()` placeholders. From the Codex: > The query parameter for prepare accepts sprintf()-like placeholders. The %s (string), %d (integer) and %f (float) formats are supported. It's not entirely obvious from that but the argument swapping formats (e.g. `%1$d`) are not supported _(in any case you have the incorrect syntax: it should be`%2$s` instead of `%2s`)_ global $wpdb; $wpdb->prepare( "SELECT * FROM location WHERE name LIKE %s OR name LIKE %s", '%'.$wpdb->esc_like('on'), '%'.$wpdb->esc_like('on').'%' ), ARRAY_A); I'm assuming 'on' might be replaced by a unknown value - otherwise `$wpdb->prepare()` isn't necessary. On an unrelated note, the second condition in your SQL makes the first obsolete.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "plugins, posts, plugin development, wp query, menus" }
Easier way to display custom post meta? I'm looking for cleaner way to display this code; basically I need to display a review score and if it has a review link to link it in, I know there is an easier way but my knowledge is lesser than my current task. So the way it should work is as follows... display game_rating, if review_link has a value then link game_rating to review_link <?php $review_link = get_post_meta( get_the_ID(), 'game_review_link', true ); if ( ! empty( $review_link ) ) : ?> <a href="<?php echo esc_html( $review_link ); ?>"> <?php endif; ?> <div class="rating-<?php echo esc_html( get_post_meta( get_the_ID(), 'game_rating', true ) ); ?>"><?php echo esc_html( get_post_meta( get_the_ID(), 'game_rating', true ) ); ?></div> <?php $review_link = get_post_meta( get_the_ID(), 'game_review_link', true ); if ( ! empty( $review_link ) ) : ?> </a> <?php endif; ?>
In situations like this sometimes it's easier to get all the data up front and then build the output. First get the link and rating, then check if the link is empty. If the link isn't empty append it to the rating. Lastly, print the rating to the page. <?php $review_link = esc_html( get_post_meta( get_the_ID(), 'game_review_link', true ) ); $game_rating = esc_html( get_post_meta( get_the_ID(), 'game_rating', true ) ); if ( ! empty( $review_link ) ) { $game_rating = '<a href="' . $review_link . '">' . $game_rating . '</a>'; } ?> <div class="rating-<?php echo esc_html( get_post_meta( get_the_ID(), 'game_rating', true ) ); ?>"> <?php echo $game_rating; ?> </div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Generating a feed of all but one category of posts I'm basing my first WP theme off a blank/boilerplate theme which generates the front page post feed using this code (which is generally present in most WP themes): <?php while ( have_posts() ) : the_post() ?> <?php get_template_part( 'entry' ); ?> <?php comments_template(); ?> <?php endwhile; ?> I have one category of posts that I don't want displayed in this feed. Knowing that category's ID number and the range of category IDs to include, what's the easiest way to get the feed to exclude one category of posts?
I think you can go even simpler in the coding. Just add the below to your **functions.php** file within your theme folder. function myFeedExcluder($query) { if ($query->is_feed) { $query->set('cat','-73,-9'); // categories 73 and 9 are being excluded } return $query; } add_filter('pre_get_posts','myFeedExcluder'); Note particularly that multiple categories can be excluded by separating them with commas. And here's the codex page on customizing feeds, but it doesn't specifically address this situation.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, feed" }
How to fix 502 errors on my WordPress site hosted on Windows Azure that only occur when I update a post? I have a Wordpress site that is hosted on Windows Azure, with the database hosted separately. Every time I try to update a post I get a 502 error, specifically: > 502 - Web server received an invalid response while acting as a gateway or proxy server. The DB provider says everything is fine - does anyone know how I can troubleshoot this problem? Oddly enough - basic reads are fine - the error only occurs when I try to update a post.
I turned on failed request tracing, and saw many entries (not errors, but entries) for Glimpse (I have wordpress running as a subdirectory of my .net site). Glimpse is not supposed to be running in production - but apparently it does. When I removed Glimpse everything worked just fine. Live and learn I guess.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "errors" }
Multiple meta_values in the pre_get_posts filter? I have a custom post type with custom fields, the one in particular is "zip". I also have an array that stores like 20 different zip codes. I want to check to see if any of those custom post types have one of those zip codes. If they do, then I want them to appear in the search results. If they don't, I don't want them to appear. How would I go about doing this..? It's driving me insane. Thanks in advance.
You will need to create two queries. The first will be one that pulls all of the custom post types in the search query. $args = array( 'post_type' => YOUR-POST-TYPE, 'posts_per_page' => '-1', 's' => get_search_query(), ); $sort_query = new WP_Query($args); $included_results = array(); You will then have to probably print out your results so you can find where the zip code is in the array. Run the loop, checking if the zip is in your zip code array (`in_array()`) and add the id to the included results array (ex: `$included_results[] = $post->ID`) Next, you will want to end and reset the query, and create a new query using the same args as before, but adding `'post__in' => $included_results`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, search, pre get posts" }
Secret keys in SCM I have a WordPress installation in a Git repository and I'm wondering, if it's safe to have the 8 "secret keys" stored in there, or if I should insert them during deploy.
Your config file shouldn't be public at all. It includes your database credentials in addition to the 8 SALTs WordPress. (The secret keys alone make it possible to brute force your log-in in a bout a week: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "security, wp config, deployment" }
Get user's ID on logout Is it at all possible to get a user's ID in a function right at the point of log out? I tried to hook it to `wp_logout`, but it just returns null when trying to get the user's info. I'm wondering if there is another hook that comes before `wp_logout` destroy's the session that would enable me to capture the ID and do something with it. I simply want to update a user meta field with the time of logout. Is there any way of doing this?
I think I figured this one out. I had misread this answer and hooked the function I wrote to `wp_clear_auth_cookie` (actually a function itself!) instead of `clear_auth_cookie` (the _real_ hook), so that wasn't working. But now using the real hook, I think it might be. Correct me if I'm wrong. Below is the function with the hook. function users_last_login() { $cur_login = current_time(timestamp, 0); $userinfo = wp_get_current_user(); update_user_meta( $userinfo->ID, 'last_login', $cur_login ); } add_action('clear_auth_cookie', 'users_last_login', 10);
stackexchange-wordpress
{ "answer_score": 10, "question_score": 1, "tags": "user meta, actions" }
For a complete backup, is it enough to copy htdocs and export database? I copied the htdocs via FTP from the server which hosts my wordpress blog. Moreover, I used phpMyAdmin to export the MySQL database. When I move to a new server, can I just create a database, run the SQL script and copy the backed up data to the new server's htdocs to rebuild the blog exactly as it was?
In general - _Yes_. Make sure that the file and directory permissions are appropriate. In case the URL of your website changes, you would have to do a find/replace. Read more about it in the links below. Also, 'update permalinks' once you have access to the Dashboard. ### References: * Codex: Moving WordPress * Codex: Changing File Permissions * Codex: Settings Permalinks Screen
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "images, sql, server, backup" }
What is the point of using archive.php instead of index.php? **Dumb Questions Ahead:** * If `index.php` and `archive.php` are practically the same thing, what's the point of having `archive.php`? * When should I ever want to use `archive.php` over `index.php`? * If I use front-page and Blog, it doesn't switch to `archive.php` which you might expect to and then use `index.php` in the place of `front-page.php`.
`index.php` and `archive.php` might be the same but don't _have to be_ the same. `index.php` will display your blog post archive and in the absence of `archive.php` (or other more specific archive files) it will display your date, author, etc. archives as well. But it doesn't have to. You can, if you want, display your archived differently that your main blog index. That is the point of those specialized files-- they allow you to alter the look of specific pages without having to write complicated conditionals into the `index.php` file. The difference between the two files is what you make of it. That difference can be a lot or none. # Reference <
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "theme development, templates, template hierarchy" }
Check for template part, else filter content In a plugin which brings its own post type to the table, I wish to handle `post_meta` by filtering `the_content` \- unless the user has provided their own `single-{post-type}.php` template. Should I run this within `the_content` filter? Or elsewhere? if ( file_exists( get_stylesheet_directory() . '/single-event.php' ) ) { include( get_stylesheet_directory() . '/single-event.php' ); } elseif ( file_exists( get_template_directory() . '/single-event.php' ) ) { include( get_template_directory() . '/single-event.php' ); } else { // filter time } If it's not in my `add_filter('the_content', 'event_filter_function', 10);` then I guess I'm wondering how else I will know at run-time whether this file exists. So is computationally expensive to run this filter and simply return $content unaltered if there is a template provided? Or is there a better way?
Two code snippets here that are pretty self explanatory: ## Add a template from the plugin if none is present from the theme add_filter( 'page_template', 'wpse110317_append_meta' ); function wpse110317_append_meta( $template ) { is_singular() AND ! file_exists( get_template_directory()."/{$template}" ) AND $template = plugin_dir_path( __FILE__ )."/{$template}"; return $template; } ## Append something to the content _until_ there's a template in the theme add_filter( 'page_template', 'wpse110317_maybe_add_filter' ); function wpse110317_maybe_add_filter( $template ) { is_singular() AND ! file_exists( get_template_directory()."/{$template}" ) AND add_action( 'the_content', 'wpse110317_append_meta' ); return $template; } function wpse110317_append_meta( $content ) { // do stuff return $content; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, filters" }
What query to append the 10 next posts? I am loading more posts with ajax when clicking on a button. There is 4 posts when you arrive on the page and everytime you click on the button, it needs to load 4 more. What query would I need to use? On my ajax.php, this is what my custom query looks like: $queryLoadPosts = new WP_Query(array( 'post_type' => 'track', 'posts_per_page' => 4 )); I also tried 'page_id' => 2, but it did not work. I also though about doing a loop and incrementing a variable and only start echoing the posts when ex: $i >3, but that would be the worst code...
You need the `$paged` param and pass it with the ajax call. $queryLoadPosts = new WP_Query(array( 'post_type' => 'track', 'posts_per_page' => 4, 'paged' => (isset($_REQUEST['paged']) && intval($_REQUEST['paged'])) ? $_REQUEST['paged'] : 1 )); First time you click the button the `paged` param must be 2, second time 3, and so on... so you need to store somewhere the last value of paged with js, use a `data-` attribute of the button can be a good idea. see Pagination Parameters of WP_Query on Codex
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query" }
after wp_insert_post need to get the post id I have a function in function.php and it does wp_insert_post. how can I get the post id which just posted? when I do wp_insert_posts, it saves a PR value (unique and it saves in post-meta table). Do I need to do "select"? like select post_id from wp-post where oid=".$oid...... etc like this? I have tried to get $post_id = wp_insert_post($new_post); $post_id = get_post($post_id) But these are not working. I am not also very good at wp join. how can I do?
$post_ID = wp_insert_post($post); ... should work, as you mentioned. From the Codex: > Returns the ID of the post if the post is successfully added to the database. On failure, it returns 0 if $wp_error is set to false, or a WP_Error object if $wp_error is set to true.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wp insert post" }
Copying theme from Localhost to Live does not copy all theme settings with it? This has happened on a number of occasions now where I move my site from Localhost to Live environment and the theme settings such as the logo, and other settings are not copied with it, so I am almost have to rebuild the site twice sometimes. Responsive is one example where this is happening as well as numerous other themes I move from Localhost to Live environment. Is there something I am missing when move the DB over? Perhaps another settings file? Many thanks
Since I found this script, I have used it for every single move I make from Localhost to Live or vice versa. It's incredibly simple to use and has worked every time. < (Review: < ) **From their site:** You must use a safe search and replace method that preserves the integrity of the serialized string lengths. A simple find and replace of a dump file for **` to, for example, **` is problematic because the length of the string changes but the indexes for the serialized strings does not. Consequently settings are lost and widgets disappear.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "themes, options, localhost" }
Query sql for truncate post_content in wp_posts table Hello all i need remove all info in Wordpress posts content and i'ld like do it from phpmyadmin with a query. I need remove only the text and images from all posts content but not the entire post, so i need know the sql query for do it, please someone can help me? Stew
1. Backup your db 2. Remeber to backup your db 3. Import the backup in another database, change wp-config.php to use this new database and see if everithing is ok. (Importing is successfull? Site appear without any change?) 4. Wordpress uses a prefix for table names. The default is 'wp_' but clever guys change it with something else. (The change is made in wp-config.php before install WP). So in my query I will use 'wp_' as table prefix, replace it with your table prefix if it's different. 5. In the new db (the one created from backup) run this query (remember to change `wp_posts` if your tables has a different prefix): UPDATE wp_posts SET post_content = "", post_excerpt = "" WHERE post_type = 'post' AND post_status <> 'inherit' AND post_status <> 'trash'; 6. Check your site and if anything goes wrong change `wp-config.php` to use the original db and then investigate the problem.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "mysql, sql" }
Remove post title input from edit page I'd like to remove the post title input on a (cpt) post edit page (backend) based on user's capabilities. I have already found Stack Overflow question dealing the problem. However, the solution in involves editing the WordPress core files. I don't like it that way. Is it possible to achieve the hiding (or removing) with a plugin? Currently I do not know or do not see how the plugin should hook into WordPress.
You can do this : add_action('admin_init', 'wpse_110427_hide_title'); function wpse_110427_hide_title() { if (current_user_can('subscriber')) remove_post_type_support('post', 'title'); } This would hide title for subscriber. Replace 'post' with your custom post type
stackexchange-wordpress
{ "answer_score": 7, "question_score": 6, "tags": "posts, title" }
post edit button on front end If you are logged-in and switch to the front-end the default Wordpress theme `Twenty Eleven` provides `edit` buttons next to every post. Pressing this button you get to the certain post's back-end post edit page. How to implement this into a custom template?
The function is `edit_post_link()` (see Codex or source). In TwentyEleven it used as follows in `content.php` edit_post_link( __( 'Edit', 'twentyeleven' ), '<span class="edit-link">', '</span>' ); You can simply use the function as indicated above (or in the Codex) in a custom template, but it must be used **inside the loop**. There's no need to perform any permission checks.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "templates, theme twenty eleven" }
Show only posts from one category on custom post type archive page I have a custom post type, called Exercises. I also have many categories within that custom post type. I use archive-exercises.php custom loop to display my main exercises page. Question: How do I modify my archive-exercises.php so it will display only post from specific category? I managed to get similar effect on my home page with regular posts: <?php query_posts('cat=93&amp;showposts='.get_option('posts_per_page')); ?>
Use the `pre_get_posts` action to modify any main query before it is sent to the database, this includes the case of your home page as well. Calling `query_posts` in the template runs a new query, overwriting the original- it's a waste of resources and can produce unpredictable results, particularly with pagination. function wpa_pre_get_posts( $query ){ if( is_post_type_archive( 'exercises' ) && $query->is_main_query() ){ $query->set( 'cat', 42 ); } } add_action( 'pre_get_posts','wpa_pre_get_posts' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, custom post type archives" }
Inconsistent title for posts I remember, I had edited some part of my theme for optimizing the title values. Currently in google I see this. Whereas when I open a post, the site name is not appended to the post title. I looked at the `header.php` of my theme and found the following line: <title><?php seotitles(); ?></title> I am using "All in one SEO" plugin and have set the title and description of each post manually and when I do so, I don't append the site name in the post name. How can I bring what I see in google and what the user sees in sync with each other?
There is actually nothing you can do about this. Google changed their algorithm a few months ago where they will sometimes determine the title in their results if they feel it's a better fit. I noticed this when working on the SEO for the last company I worked for. When searching "channel letters detroit" the results gave "Channel Letters - Detroit Sign Company SIGNARAMA Troy" for < while the page title is "Detroit Channel Letters, Fast Fabrication & Cost Effective | SIGNARAMA". Joost de Valk from Yoast (Author of WordPress SEO, which is very similar to All in one SEO) actually explains a little more of this in Why Google won't display the right page title.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "title, seo" }
Access last visit time to a post Is there any function or a way to access the time of last visit to a post by a visitor?
You can put a small script in your single.php that updates a custom field with the current time. update_post_meta(get_the_ID(),"last_visit",time());
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, date time" }
Where is the code for "Front Page Template"? I'm using the TwentyTwelve theme. For my static front page I'm using the "Front Page Template", but I want to modify it so it doesn't include the page's title on the rendered page itself. So I went looking for the template file for "Front Page Template" but it's not in the theme. I grepped for "Front Page Template" in the theme directory and got no hits. I poked around other locations in the WP hierarchy but can't find it. Where is it?
look in page-templates (folder) **front-page.php** EDIT: you can find page content in theme directory **content-page.php**
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "templates" }
Google maps .gm-style div now displays as block, thus breaking the map recently my Wordpress page with Google Maps started displaying markers in an odd fashion- look! !enter image description here The problem is- Google changed they code and added this baby into the code: .gm-style div { display: block; } Overriding the code with, let's say, `display:inline-block !important;` doesn't work, since a new display:block is being automatically generated by Google! (Picture below) !enter image description here The site itself is here if anyone wants a peek: `
find this in file: `/wp-content/themes/rentbuy/js/scripts.js` <div class="overlay-simple-marker" … and replace it with: <span class="overlay-simple-marker"
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "google" }
Add pages content to startpage through custom menu I would like to be able to add page content onto the startpage (index.php). But only the pages that i've added in custom menu, and in that order too. I've been searching for a while now, but can't find anything close. Big thanks to any one that can lead me in the right direction.
You can use `get_nav_menu_locations` and `wp_get_nav_menu_items` to get your menu items. $locations = get_nav_menu_locations(); $nav_items = wp_get_nav_menu_items($locations['your-menu-slug']); You can then process `$nav_items` to display your page content. It can get complicated but it does work.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, pages, navigation" }
PGP-Encrypt system-generated notifications I was wondering if there is a way to get Wordpress to encrypt notification mails ("Please moderate ..." and so on) using PGP. I have found a bunch of plugins providing PGP-encrypted eMail forms, but that's not what I was looking for, as I want the system mails to be encrypted, not the user mails. Is there any plugin or modification that does this that I have not found?
There's a small PGP plugin by Tim Nash on GitHub (but it's not in the official Wordpress repository, it needs to be manually copied to wordpress plugin directory). It's a wrapper using php-pgp library for encryption. The article where I found this link is "Encrypting emails with PGP and WordPress". This is the only Wordpress solution I have found so far. I was also digging into the subject and I'm trying more generic approach - extending PHPMailer to support PGP encryption. However, this requires some more testing to support email in both text and html format, PGP/MIME, attachments etc. so this is not ready to be published yet.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugins, notifications, encryption" }
how to check if given page is active page I am building my own custom menu for custom post type. I have a loop and I need to know if given item is active one. How to this properly? How to compare if given items address (slug, permalink, id or some other appropriate option) is the one that is currently loaded? $args = array('post_type' => 'services'); $services = new WP_Query( $args ); $cnt = 0; if( $services->have_posts() ) { while( $services->have_posts() ) { $services->the_post(); // HOW TO CHECK IF $services is the active page?
Use `get_the_ID()` before you start the loop, then compare: $original_id = is_singular() ? get_the_ID() : 0; $args = array('post_type' => 'services'); $services = new WP_Query( $args ); $cnt = 0; if( $services->have_posts() ) { while( $services->have_posts() ) { $services->the_post(); if ( get_the_ID() === $original_id ) echo 'This is me!';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
proper syntax of getting wp-admin pages/links i cant seem to find the codex for my situation. normally, i use `get_bloginfo('template_url')` to get to the template path, but this time i need to get to some **WP-ADMIN** pages. i created a custom navigation bar on my `wp-admin` and everything is working fine. i just need to get the links for the ff: * /wp-admin/upload.php * /wp-admin/index.php * /wp-admin/edit.php?post_type=page what is the proper syntax `getting` the **path** to these locations get_bloginfo('admin_url')/wp-admin-upload.php // sample only, just to express my point.
Use `admin_url()`: admin_url( 'edit.php?post_type=page' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "paths" }
Where is New Relic API key? I've installed Total Cache plugin in my wordpress application and it suggested me to create a New Relic account. I've done it, but now the plugin ask me for an API key, and no idea of where to find it. I thought it would be the license key, but not. Anyone know where is it?
This solved the problem: 1. Select (account name) > Account settings > Integrations > Data sharing > API access. 2. Click Enable API Access, and then put it on the required field in WP Total Cache general settings.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin w3 total cache" }
Private Posts/Pages & Search I have a site up where there is one private page and one private post. When logged is as admin, i can view both of these, and they even appear in the search. However, when logged in as an editor, I can still see the posts, but they don't appear in the search. I found this a bit strange, was wondering if anyone has experienced this or knows how to make the private pages and posts appear in the search when logged in as an editor?
This is the default WordPress behavior. > Private posts are automatically published but not visible to anyone but those with the appropriate permission levels (Editor or Administrator). > > WARNING: If your site has multiple editors or administrators, they will be able to see your protected and private posts in the Edit panel. If you want to show private posts on the front-end of the site to logged-in editors you can add this code to **functions.php**. add_action('pre_get_posts','filter_search'); function filter_Search($query){ if( is_admin() || ! $query->is_main_query() ) return; if ($query->is_search) { if( current_user_can('edit_private_posts') ) { $query->set('post_status',array('private','publish')); } } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, pages, search, private" }
How to show custom post template from single page? We know that in WordPress the default post template file is `single.php`. Now, I have one category name "members" and want _members_ posts to show a custom template, like `content-members.php`. I can do that via custom post template plugins. but is there a way to make that without plugins? Maybe we can do that like this: <?php if ( is_category( 'members' ) ) { get_template_part( 'content', 'members' ); } else { get_template_part( 'content', 'common' ); } ?> I tried this already, but it's not working and I think category is not triggering here.
I believe you might need to use in_category() instead of is_category(). in_category() checks if the current post is in a category, is_category() checks if it's a category archive page.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "custom post types" }
Install old version of plugin from admin panel? Is there a way to install an old version of a plugin that is hosted on the WordPress.org plugin repository from the admin panel? I know that you can easily go to the WordPress.org plugin repository, grab any version of any plugin you want, FTP the files onto your website, and then activate from the Plugins admin page. However, I was wondering if there is a way to install a plugin using the Plugins -> Add New page and choose a version other than the latest. I am helping someone out with testing, and I have Administrator access to their admin panel, but not FTP access.
I think you can download the older plugin version in zip format and upload it from admin panel from Install Plugins -> Upload option.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, wp admin" }
Removing template part when not on homepage if / else Thank you in advance for any help! What I am trying to do is remove a template part from my home page after the user clicks on the pagination links from the posts, right now my template part serves as a "hero" or "featured" area, and I would like it to go away when the user looks at older posts, eg the pagination, here is what I am doing so far and it is not working, thanks! <?php if( is_home() || is_front_page() ) : ?> <?php get_template_part( 'hero' ); ?> <?php else : ?> <?php get_template_part( 'blank' ); ?> <?php endif; ?> as you can see i created a blank template , not sure if this was necessary , does it need to be inside the loop? thank you!
I believe what you need is `is_page()`. if (is_paged()) { // page 2 or later of an archive } else { // only the first page of an archive } With your code, I think but am not 100% sure, that you want: if( !is_paged() && ( is_home() || is_front_page() ) ) : get_template_part( 'hero' ); else : get_template_part( 'blank' ); endif;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pagination, homepage, conditional tags" }
Access to Instance Variables from WP_Query If I make a query to the wordpress database to pull the five most recent posts of some kind, and I would like to do a different treatment to each of them, is there a way to access the individual instance objects? For instance, if I want to do something to the second post object, is there a way to access the object by something along these lines? $query = new WP_Query( $args ); $query[1] => access to the second post object from the query
$query = new WP_Query( $args ); if ( $query->have_posts( $query->have_posts()) ) : while( $query->have_posts()) : $query->the_post(); global $post; switch ( $query->current_post ) { case 0 : // first post object is in var $post; echo 'The first post title is ' . $post->post_title; break; case 1 : // because we are insed the loop we can use all the post template tags echo 'The second post title is ' . get_the_title(); break; .... } endwhile; endif; wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "wp query" }
update_user_meta on registration but only for default role type So I am running the following to update user meta on regsitration: function set_user_rcp_default_subscriber($user_id) { update_user_meta( $user_id, 'wp_user_level', '0' ); update_user_meta( $user_id, 'rcp_subscription_level', '1' ); update_user_meta( $user_id, 'rcp_status', 'active' ); update_user_meta( $user_id, 'rcp_expiration', '2014-06-30' ); } add_action("user_register", "set_user_rcp_default_subscriber", 10, 1); However, I only want this to apply to users that are registered as the default type (subscriber in my case). Users that are registered with a different role type I dont want to update with these meta values. Any help very much appreciated. Many thanks.
Here is what you need to do: function set_user_rcp_default_subscriber($user_id) { $user = new WP_User( $user_id ); foreach( $user->roles as $role ) { if ( $role === 'subscriber' ) { update_user_meta( $user_id, 'wp_user_level', '0' ); update_user_meta( $user_id, 'rcp_subscription_level', '1' ); update_user_meta( $user_id, 'rcp_status', 'active' ); update_user_meta( $user_id, 'rcp_expiration', '2014-06-30' ); } } } add_action("user_register", "set_user_rcp_default_subscriber", 10, 1); We need to loop through it because potentially a user can have multiple roles.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user roles, user meta" }
Exceprt not displaying I am using a custom template homepage in which I want to display some excerpt from a category but it's not displaying as I code for just `the_excerpt`. I have a confusion too, they say the `the_excerpt` should be used within loop. What is the main reason of loop? As my code is wrapped within the loop, am i missing something?
According to your question: > What is the main reason of loop? the clearest answer comes from official documentation: > The Loop is PHP code used by WordPress to display posts. Using The Loop, WordPress processes each post to be displayed on the current page, and formats it according to how it matches specified criteria within The Loop tags. Any HTML or PHP code in the Loop will be processed on each post. > > When WordPress documentation says "This tag must be within The Loop", such as for specific Template Tag or plugins, the tag will be repeated for each post. It's correct put within the loop `the_excerpt()` template tag. For example a loop code it might looks like: <?php if( have_posts() ) : while( have_posts() ) : the_post(); ?> <p><?php the_excerpt(); ?></p> <?php endwhile; else: ?> <p>No posts were found</p> <?php endif; ?> To help you with your issue, it could be a good idea posting the whole code
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop" }
How to use classes declared in another plugin? I'm developing a Wordpress Woocommerce plugin. On my local environment it works fine but I have problems when adding the plugin to a replica of the prod environment. I am new to wordpress and not very familiar with web dev (I'm a Java programmer). In the plugin file, I instantiate a class from the Woocommerce plugin package like this: $coupon = new WC_Coupon($some_code); In the local environment (php 5.4.10 , Woocommerce 2.0.13, Wordpress 3.6) it's fine. In the production environment (php 5.4.10 , Woocommerce 1.6.5.2, Wordpress 3.4.2) I have the following error: Fatal error: Class 'WC_Coupon' not found I have tried including the file where the WC_Coupon class is defined but then the error becomes Fatal error: Cannot redeclare class WC_Coupon So what is the proper way to use classes declared in another plugin? Note: upgrading is not an option at the moment.
You have to check if the class exists, but before that you have to _wait_ that all plugin are loaded: no one can assure that your plugin is loaded after WooCommerce. For run a code from plugin when all plugin are loaded hook into `plugins_loaded` hook. Be aware that you cannot use this hook in a theme, because when theme load that hook was already fired. add_action('plugins_loaded', 'my_coupon_init'); function my_coupon_init() { if ( class_exists('WC_Coupon') ) { $coupon = new WC_Coupon($some_code); // some code here } else { add_action('admin_notices', 'wc_not_loaded'); } } function wc_not_loaded() { printf( '<div class="error"><p>%s</p></div>', __('Sorry cannot create coupon because WooCommerce is not loaded') ); }
stackexchange-wordpress
{ "answer_score": 11, "question_score": 12, "tags": "plugins, oop" }
get_results using wpdb I'm trying to retrieve information on my database. I wanted to display all `pages` using this statement, but I'm getting a blank `ARRAY` global $wpdb; $result = $wpdb->get_results ( " SELECT * FROM $wpdb->wp_posts WHERE post_type = 'page' " ); echo $result; // display data Output: ARRAY **EDIT** : After changing below suggestions, I'm now using this. but I still don't get any results: global $wpdb; $posts = $wpdb->wp_posts; $result = $wpdb->get_results( " SELECT * FROM $posts WHERE 'post_type' = 'page' " ); foreach ($result as $page) { echo $page->ID.'<br/>'; }
global $wpdb; $result = $wpdb->get_results ( " SELECT * FROM $wpdb->posts WHERE post_type = 'page' " ); foreach ( $result as $page ) { echo $page->ID.'<br/>'; echo $page->post_title.'<br/>'; }
stackexchange-wordpress
{ "answer_score": 27, "question_score": 19, "tags": "database, query, wpdb" }
Best way to extends core classes in theme? I need to add functions to my WP_User objects, to be used like this : <?php // in my templates : $user = new User($id); $user->sendHelloWorldEmail(); // in my functions.php class User extends WP_User { public function sendHelloWorldEmail(){ // do stuff ... } } My question is : what is the best way to overload Core Classes (WP_Post/WP_User...) ? And : is it a good idea, or is there a better way to achieve this (with objects programming) ?
What you are doing will work, and is correct as far as the PHP goes. Whether it is a good idea or not really depends on what you are doing _specifically_ and whether you can do it with hooks\-- actions and filters-- instead. If you can do it with hooks you probably should but your question doesn't have detail enough to really allow for a great answer. I don't think that extending Core classes is "wrong" necessarily but you can set yourself up for higher than normal maintenance as your extended class may need to change if the parent does, so be aware. Its the "fragile base class" problem. This is not really "overloading", by the way, and in PHP "overloading" is not really that anyway.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "php, core, oop" }
Where to add css file that I want my forms to use? Where and how should I add the css file that I want my forms to use? Thank you!
Use `wp_enqueue_style` to add additional stylesheets to a theme. Additionally, you can use it with a Child Theme to preserve your edits in case the original theme is updated. function wpa_form_style() { wp_enqueue_style( 'my-form-styles', get_stylesheet_directory_uri() . '/my-form-styles.css' ); } add_action( 'wp_enqueue_scripts', 'wpa_form_style' ); or if you only need your styles for a specific page, conditionally enqueue it with a check for `is_page()`: function wpa_form_style() { if( is_page( 'contact' ) ){ wp_enqueue_style( 'my-form-styles', get_stylesheet_directory_uri() . '/my-form-styles.css' ); } } add_action( 'wp_enqueue_scripts', 'wpa_form_style' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "forms" }
mo / po translation files does not seem to work I have a theme that was bought from themefuse and they say it supports localisation using a plugin called CodeStyling Localization However even though I make the necessary steps to translate strings in the theme, the translated texts do not appear in the frontend. The steps I have taken: 1. installing plugin 2. scan the theme 3. translate a few words 4. build "mo" file from plugin menu 5. empty cache + refresh ... no result Any ideas?
Check the `wp-config.php` file and see if your language is defined : define('WPLANG', 'your_language'); You could add this if you're still stuck: add_action('after_setup_theme','wpse_110727_translate_theme'); function wpse_110727_translate_theme() { load_theme_textdomain( 'textdomain', get_template_directory() . '/languages' ); $locale = get_locale(); $locale_file = get_template_directory() . "/languages/$locale.php"; if ( is_readable( $locale_file ) ) require_once( $locale_file ); } Just put the translation files into a repertory called `/languages/` and upload all files in the root of your theme. See if it works now. Hope this helps. **EDIT:** 'textdomain' is the word used in all translation strings : `_e('some content','textdomain');`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "translation" }
woocommerce buy button My site is a affiliate and I want woocommerce buy button to open up website in a new tab. As i go through the code i see its functions like do_action, calling functions. don't know where are the function based. I checked functions file too but cannot find it. How can i break it down, that which components of woocommerce is being called and editing that function like i want to open the external website in another window.
I found a way a long time back, so updating that everyone knows. I did a search for title of button i.e 'Buy Now' and the file which had it, i copied it into my child theme. From there i updated the text and all went well!
stackexchange-wordpress
{ "answer_score": -1, "question_score": -1, "tags": "plugins" }
Display post taxonomies tree I was able to get all the items of a custom taxonomy for a post, like this: $args=array('orderby'=>'parent',"fields" => "all"); $term_list = wp_get_post_terms($post->ID, 'tvr_amenity', $args); My problem is that i would like to show the tree (respecting the parents) So i would like to get them ordered by name and parent but i cant find anything related on codex.. any idea how?
What about: $taxName = "tvr_amenity"; $terms = get_terms($taxName,array('parent' => 0)); foreach($terms as $term) { echo '<a href="'.get_term_link($term->slug,$taxName).'">'.$term->name.'</a>'; $term_children = get_term_children($term->term_id,$taxName); echo '<ul>'; foreach($term_children as $term_child_id) { $term_child = get_term_by('id',$term_child_id,$taxName); echo '<li><a href="' . get_term_link( $term_child->name, $taxName ) . '">' . $term_child->name . '</a></li>'; } echo '</ul>'; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom taxonomy, terms, get children" }
Form Object Gravity Forms Gravity Forms. I try to manipulate the form fields before they are rendered with add_filter("gform_pre_render", "my_function", 10, 5); function my_function($form){ ... $form["fields"][0]["content"] = 'This is a html-block' } Like this, I can pass the html-block's content assumed the html is the first field on the form. How can I target a field by `id`? Let's say the above html-block-field has the field id `13`.
According to this page about the form fields object, it looks like you'd need to do something like this: $my_id = '37'; foreach($form['fields'] as $field){ if($field['id'] == $my_id){ $field['content'] = 'This is a html-block'; } } where `$my_id` is the id of the field you are targeting
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin gravity forms" }
Wordpress VIP realpath Alternative? I am running a scan for a site to be proposed to wp vip. The only error I am getting is : > Warning: Returns canonicalized absolute pathname header-payroll.php require_once realpath(dirname( **FILE** )). '/header.php'; What would be the fix for this. I believe I would need an alternative for "realpath"?
I don't know what "wp vip" wants or needs, but you should be loading files by means of `get_template_part`, `locate_template`, `site_url`, or `home_url` and I am guessing that using one or more of those is what the "scan" wants. It is hard to say exactly which since you posted only the error and not the source that goes with the error.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "mysql, wordpress.com hosting, paths" }
What hook to use to redirect based on $post Trying to add an action to redirect based on if user is not logged in and is accessing certain post types. Problem is, during template_redirect, `$post` is NULL and other ones the headers seem to have already been sent so it won't redirect. What would be the appropriate action to use here? add_action( 'template_redirect', 'mytheme_restrict_user_content' ); function mytheme_restrict_user_content(){ if (!is_user_logged_in() ) { $restrict = false; $restricted_post_types = array('documentlibrary', 'events'); if ( in_array( $post->post_type, $restricted_post_types ) ){ $restrict = true; } if ($restrict){ auth_redirect(); } } }
add_action( 'pre_get_posts', 'mytheme_restrict_user_content' ); function mytheme_restrict_user_content( $query ){ $restricted_post_types = array('documentlibrary', 'events'); if ( is_main_query() && is_singular($restricted_post_types) && ! is_user_logged_in() ) { $redirect = set_url_scheme(' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); wp_redirect( wp_login_url($redirect, true) ); exit(); } } I don't use `auth_redirect` because that function check if the user is logged in, but we already know that user is not logged in.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "hooks, redirect, actions" }
returning 404 page error on form submission I have decided not to use a plugin to create a simple contact form on my site and used some php code to do the same job. This was so i could style the form exactly how I wanted to. However when I test the form and submit it, the user is sent to the 404 error page despite the url at the top of the browser indicating the contact page that exists. I'm not sure why that would be the case.? I followed this tutorial to create the template page on my site < Here is the form on my test site <
change input name for name field to contactName or cName etc. <input type="text" name="cName" id="name" placeholder="Your name" autocomplete="off" tabindex="1" class="txtinput" value=""/>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "404 error" }
Remove Categories / Tags From Admin Menu I want to remove or hide Categories / Tags submenu under Posts in the Admin Menu. I know this works with the themes submenus: `remove_submenu_page( 'themes.php', 'widgets.php' );` The same doesn't seem to work for posts unfortunately: `remove_submenu_page( 'edit.php', 'edit-tags.php' );` I'm using the admin_menu action: `add_action( 'admin_menu', 'function_call' )` Do I need to add something else?
add_action('admin_menu', 'my_remove_sub_menus'); function my_remove_sub_menus() { remove_submenu_page('edit.php', 'edit-tags.php?taxonomy=category'); remove_submenu_page('edit.php', 'edit-tags.php?taxonomy=post_tag'); }
stackexchange-wordpress
{ "answer_score": 17, "question_score": 11, "tags": "posts, customization, admin menu, sub menu" }
Create custom page and custom menu I'm trying to do one custom menu at my wordpress admin panel. My plans are: make and menu, to add some contents at a custom page, like "people" and their names, etc... I wanna make it with php. I used this only to view whats happen: add_action('admin_menu', 'register_my_custom_submenu_page'); function register_my_custom_submenu_page() { add_submenu_page( 'tools.php', 'My Custom Submenu Page', 'My Custom Submenu Page', 'manage_options', 'my-custom-submenu-page', 'my_custom_submenu_page_callback' ); } function my_custom_submenu_page_callback() { echo '<h3>My Custom Submenu Page</h3>'; } It added an page, inside tools menu, what can I do to create on an exclusive menu?? On `my_custom_submenu_page_callback`, what can I do to work with embedded PHP code? like `mysql_query` and stuff?
If I understand you, what you are doing is almost correct. You need `add_menu_page` instead of `add_submenu_page` add_action('admin_menu', 'register_my_custom_submenu_page'); function register_my_custom_submenu_page() { add_menu_page( 'My Custom Submenu Page', 'My Custom Submenu Page', 'manage_options', 'my-custom-submenu-page', 'my_custom_submenu_page_callback' ); } function my_custom_submenu_page_callback() { echo '<h3>My Custom Submenu Page</h3>'; } As far as the "embedded" PHP, you already have it. Everything in that code is PHP. You can add whatever other PHP you want inside that callback (`my_custom_submenu_page_callback`) and it should work so long as the PHP itself is valid and you watch out for variable scope and such. Your capability-- `manage_options`\-- may need to be changed. That depends on how you want it to work.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus, wp admin, dashboard" }
How to show a dynamic_sidebar if main content content's height is > a set amount? I'm looking to add a second dynamic_sidebar to a theme's sidebar.php that will only be displayed if the height of my main content area is greater than a certain amount. If I had some magic hybrid of jQuery and php, and I wanted this to happen if the main content area (#content) was taller than 700px I'd do something like: if ( jQuery('#header-wrap').height() > 700 ) { dynamic_sidebar( 'sidebar-extra' ); } Is this possible using real phg? I know I could use jQuery hide() inside that conditional, but I'd rather not load the sidebar and mess with my layout if I didn't have to.
The "magic hybrid of jQuery and php" is called "AJAX", at least in this case. You will need to use the Javascript to conditionally make another request to the server. The PHP runs on the server and so has no idea how tall the page is. The Javascript runs in the browser and can work out the window height but can't run the PHP directly. The only choice is AJAX. WordPress has an AJAX API, that makes AJAX requests very easy. There are plenty of examples in the Codex for using the AJAX API and plenty of questions here about it as well. Get started. If you have trouble, edit your question with the specifics.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, theme development, jquery, sidebar" }
Custom post type archive page for multiple post types Hi I am working on a archive page which I can use for multiple custom post types. I need to make a variable in the `$args` array which can change to the `post_type` name on the basis of `<?php post_type_archive_title(); ?>` So something like this: <?php $post_type = post_type_archive_title(); $args = array( 'post_type' => $post_type, 'orderby' => 'title', 'order' => 'ASC', 'caller_get_posts' => 1, 'posts_per_page' => 20, ); query_posts($args); ?> But this doesn't work. Does anyone know how I can fix this?
From WordPress Codex: > **Function Reference/post type archive title** > > This is optimized for archive.php and archive-{posttype}.php template files for displaying the title of the post type. "Title of post type" is the label, not the post type registered name. You can get the registered post type name using `get_queried_object();` like this: <?php $obj = get_queried_object(); $post_type = $obj->name; ?> I see in your `$args` array, the `caller_get_posts`, if you are using WordPress 3.1+, i suggest you to use `ignore_sticky_posts` that replaced the previous one. Look this ( pagination parameters ). Maybe i'm wrong maybe not, if you have any problems, reply here : )
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, query posts, variables" }
Custom post type menu button color If I create a Custom Post Type I can change the icon used in the dashboard with this 'menu_icon' => [YOUR FILE PATH HERE] . '/images/portfolio-icon.png', // Icon Path Is it possible to change the color of the button in the dashboard.
If I'm understanding correctly what your wanting to do you'll need to override the CSS that is in `/wp-admin/css/colors-fresh.css`. To change the default state of a single button you can just add CSS like this #menu-posts-testimonials-widget { background: red; } this is an example with the `testimonial widget plugin` you can inspect the element to find out the id of the element and base your CSS off that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types" }
Where is the "Posts"/"Blog" template? I want to modify the "Posts" template. But I can't find it's location, I believe it's unrelated to my theme. Where is it located? Could I copy it and create an identical template in my theme so as to not mess around with the original?
**Posts** (note the plural) template does not exists. The archive of standard post type, when is not a more _specific_ template (date archive, author archive, taxonomy archive) is handled by: `home.php` (and if this file doesn't exist) by `index.php`. If you intend **Post** (note the singular) the right template file is `single.php` Once understood this, to modify the template follow @JMau answer: create a child theme. # Edit the informations above are not a _secret_ , but are fully accessible in the Template Hierarchy page of Codex as @hereswhatidid says in the comment below.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, blog" }
Make the plugin directory recognize new version numbers I updated readme.txt Stable Tag and tagged versions 0.2, 0.3 and latest 0.3.1 in SVN. After checkin, the new version is recognized only partly: * On the dev-tab it links to the latest version (0.3.1) in the svn repository. * The link-text still reads "0.1" * The download button reads "Download Version 0.1" * All other versions are listed under "other versions" Plugin: < **Question** : How to make the directory recognize version 0.3.1 ?
You need to make sure you update version numbers in all relevant locations: * `\trunk` * `readme.txt` * `pluginfile.php` * `\tags\{tag}` * `pluginfile.php` * (note: you _should_ update `readme.txt`, but outside of trunk, it's only for aesthetics) In this case, you updated `readme.txt` in `\trunk`, but you didn't update the Plugin file in `\trunk` or in `\tags\0.3.1`.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugins, plugin development" }
Which modification to login only certain role? I have created a special role in WP admin and now I would like to allow to login to certain frontend page only people with this role. How to do that? I still want be able to login for all people for other areas.
Elaborate plugins exist to restrict page access based on a user role or other settings. However, I guess the following code is as simple as it’s gets for checking a user role. <?php global $current_user; if ( is_page( 'some-page' ) && in_array( 'some-role', $current_user->roles ) ) { // Show the page } else { // Howdy, stranger! Nothing to see here. } ?> Note: this code could go into your theme’s template files such as `index.php` or `page.php`. Be aware that switching themes would remove the user role access restriction. Solution? Move this functionality to a plugin. Update: G. M. provided a plugin version in his answer.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "login" }
Where is the template from the_post_thumbnail()? My content.php is used both for my front page than for my single posts. The problem is that it calls the thumbnail with "the_post_thumbnail()" and the thumbnail returns with a particular width and height (`<img width="308" height="208"...`. I need to change get a different width and height depending if is_single(). Where is the template for the thumbnail or how can I archive this?
Assuming that this is a theme that you can edit-- ie. one of your own creation-- `the_post_thumbnail` accepts an argument for size. the_post_thumbnail( $size, $attr ); Just give it the size you want, for example: the_post_thumbnail('full');
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "post thumbnails, thumbnails" }
Need to call this php function inside a modal window from text widget Need to call this php function inside a modal window from sidebar text widget <?php echo get_post_meta( $post->ID, 'link', true ); ?>
There are several examples on the net, however I use this: <?php //functions.php add_filter( 'widget_text', 'php_parser', 100 ); function php_parser( $html ){ if( strpos( $html, "<"."?php" ) !== false ){ ob_start(); eval( "?".">".$html ); $html = ob_get_contents(); ob_end_clean(); } return $html; } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "custom field, twitter bootstrap" }
How can I access specific posts brought back by query_posts? Specifically, I am bringing back the 7 most recent posts in Category A, but then I want to put the first posts thumbnail in `<div id=A>` and the second post's thumbnail in `<div id=B>` and so on for the seven posts. If this was an array, I would simply use the array position inside of the `<div>`, but I'm not sure how to access the individual posts once I have brought them back with query_posts. Any ideas?
Why not just use a counter and then conditional logic? $i = 0; while($loop->have_posts()) : $loop->the_post(); if($i === 0){ echo '<div class="a">'.other_stuff().'</div>'; } elseif($i === 1){ echo '<div class="b">'.other_stuff().'</div>'; } else { echo '<div class="default">'.other_stuff().'</div>'; } $i++; endwhile;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, query posts, array" }
How to create custom authors links I would like to create custom authors links that lead to the page specified by the author. Instead of ` for example ` How can I do that?
You can use `author_link` filter to change the author's link add_filter( 'author_link', 'wpse110967_author_link', 10,2 ); function wpse110967_author_link( $link, $user_id ){ //Retrieve authors url from user meta $_link = esc_url( get_user_meta( $user_id, 'wpse110967_author_link', true ) ); if( $_link ) $link = $_link; return $link; } In the above example its assumed that you've stored the author-specified url as user meta with the key `wpse110967_author_link`. If no url is found, it fallback to the default WordPress url.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "urls, author" }
Is W3 Total Cache supposed to delete the local files after they are uploaded to CDN? My site hosts/sells hundreds of photos. To optimize the loading of each image in the front-end I decided to use CDN. The plugin I'm using for that is W3 Total Cache. My question is; is it supposed to delete the images after they are uploaded? I was hoping CDN would act like an image hosting too so that my hosting wouldn't have to store the images. Does CDN allow that or it requires retaining a copy of each image in the local server?
The CDN doesn't allow or disallow anything - it doesn't care what you keep on your server. W3 Total Cache does not remove local images after copying them to the CDN - and nor should it. What would happen if your CDN disappeared, or corrupted, or increased it's prices? You'd lose all of your image files.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, plugin w3 total cache, cdn" }
How to set up multiple taxonomies for groups of posts I have a site that has several types of posts, with categories for each: a News section (categories: Local, International, Breaking), a Video section (categories: Music, Kids, Holidays), and a Photo section (categories: Wedding, Portrait, Landscape). Unfortunately out-of-the-box, Wordpress is set up for a group of posts. But I need a way to present the various sections/categories in the admin (and set up in my code) in a simple clear way. I think I should set up custom post types for each of the main types of posts (News, Video, Photo) and then custom taxonomies assigned to each of those... is that right? Just want to find the most flexible, correct way to accomplish what I'm trying to do. The user should always be able to edit the categories for each type of post, and ideally I'd like the flexibility for the user to add new types of posts if possible. Thank you.
If you are looking to create custom taxonomies you can take a look on WCK plugin, where the Taxonomy Creator allows you to easily create and edit custom taxonomies for WordPress without any programming knowledge. It provides an UI for most of the arguments of register_taxonomy() function.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, categories, custom taxonomy" }
Trim Post Content on Home Page Whenever I try out a new theme, I select it depending upon preview, which shows latest posts on Home Page, having only trimmed content with featured image and not all long post content. However, when I install the theme on my test system, the preview shows full length content, instead of the preview. How can I solve this problem?
On your theme folder, open the `index.php` (or, `home.php`, or, `front-page.php`), and find, if there is a function named: the_content() Just change it to: the_excerpt() **P.S.:** If you can't find `the_content()` in the mentioned file, try searching `content.php`, and in this case, change it with caution. Because in theme TwentyTwelve, it's used with conditional tags for different pages.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, homepage, previews" }
Add meta tag to search results In the search results I use author_name=something in the url to restrict the results. The Problem is that domain.com/?s=searchterm and domain.com/?s=searchterm&author_name=something have the same meta tags. How can I add the author_name value to the meta tags?
Well I am asuming you want to amend the `<title>` tag? Add this in functions.php add_filter('wp_title', 'my_custom_page_title'); function my_custom_page_title($title) { global $s; if( isset($_REQUEST['author_name']) && is_search() ) { $title = 'Search Results for '.$s.' from author '.$_REQUEST['author_name']; } return $title; } If `$s` returns blank replace that with `$_REQUEST['s']`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "search, user meta" }
Broken Media Library I'm trying to upload media using the media library. I uploaded a couple of images several months back, and the library worked fine, these images are still available as normal through the WP backend. However, any new documents of any kind cannot be viewed due to a "failed to load" error. They're not accessable via embedded links (< or attachment pages but I can see them when I click 'Edit->Edit Image' for a media item (the image source is '/wp-admin/admin-ajax.php?action=imgedit-preview&_ajax_nonce=46c2917e48&postid=650&rand=98186'). The permissions on my wp-uploads directory are 777 and I'm totally at a loss as to why this isn't working.
I'd moved the root of my site from `/blog/` to `/` and not changed it in the general options. Everything seemed to work fine apart from the media library. Correcting the path solved the problem.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, uploads, media, media library" }
How to tune search argument in WP_Query to show only exactly the same results? Right now I am using this: $args_search = array( 's' => $search, 'post_type' => array( 'post' ) ); $wp_query = new WP_Query( $args_search ); But the problem is that it shows everything. E.g. if `$search` is just `"2386"` and I have in my db 3 posts: `"12386111"` `"23861111"` `"11112386"` I will get 3 results. But I want to get 0 results. because it's not a full match. Only if the search is `23861111` then I need to get the 1 result 23861111. Or when it is `11112386` I need to type the full `11112386` as a $search variable and not only 2386 or 238 to get the result `11112386` How to change my query to get the results as I want instead of everything that contains the search string?
$args_search = array( 's' => $search, 'exact' => 1, 'post_type' => array( 'post' ) ); There is no docs in Codex for 'exact' param, but best (sure the most reliable) docs is the code itself. See the line 2200 of query.php A limitation: if you have spaces on the search argument it will not work, because `WP_Query` consider search term with spaces as different search terms. So maybe you can use: $args_search = array( 's' => $search, 'post_type' => array( 'post' ) ); // if no spaces in search we put exact argument if ( count(explode(' ', $search)) == 1 ) $args_search['exact'] = 1; A note on your code. Right `'post_type' => array( 'post' )` not 'posts' (plural) as you posted.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "query" }
Where is the template for the 'standard' format of a post in the theme twentythirteen? I have selected the 'standard' format for a post: !enter image description here I am now trying to edit the layout of posts, in index.php I can see the following line: get_template_part( 'content', get_post_format() In the directory of twentythirteen I see several content pages which I am assuming is the post layout for the different formats I can select in the post. * content-aside.php * content-audio.php * content-chat.php * content-gallery,php * content-image.php * content-link.php * content-none.php * content-quote.php * content-status.php * content-video.php I would have expected to see a content.php or content-standard.php, but I can't find anything that affects the layout. Where is this file (if it exists)?
WordPress Twenty Thirteen uses default content.php file for the display of standard post format. Other post formats uses their corresponding files for display of content. In absence of particular template for post format, default content.php is used. The content.php file should be located at **wp-content/themes/twentythirteen/content.php**
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "templates, get template part" }
wp_redirect only works for external pages I want non logged in users to be redirected to the homepage which has a login/register form. After logging in all pages will be accessable. I've added the following code to my header.php <?php if( !is_user_logged_in() ) wp_redirect(' ); exit(); ?> This worked locally (with a localhost url) but after uploading the site to a test subdomain it's causing an error: ERR_TOO_MANY_REDIRECTS If I change the url to something else the redirect is working again but for some reason it breaks when replacing the url with the url of the homepage/site. Thanks for your help.
Next should be in a comment, not in a answer, but is too long, so I'm sorry posting here and hope it helps. You don't post the code, but it seems you are experiencing and endless redirect. Usually this happen when: 1. The page is opened, user is not logged and so redirect 2. The page is opened again, user is not logged and so redirect again Luckily TOO_MANY_REDIRECTS error come or point 2. will repeat endless. You have 2 solutions: 1. When redirect from a page, make sure to redirect to a page that not trigger the redirect again 2. If the previous is impossible add to redirect url a variable like '?noredirect=1' and before redirect check for this $_GET var If I'm wrong, please post the code and debug informations and maybe someone can better help you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp redirect" }
Google Analytics always shows at least two page views per visit - What can cause this? I'm using Google Analytics on my wordpress blog, and I'm seeing some suspicious numbers: * very low bounce rate (less than 1%) * when doing the live view, I always see page views as a multiple of two My other blogs do not show this behavior. My suspicion is that the page count is sent twice to google, but I have no idea why this would be the case. I'm using a plugin called "Google Analyticator" to track my blog. To the best of my knowledge (I looked through my template's files), there are no "direct" calls to Google. What can I do to further track down this issue?
You shouldn't have a call to `wp_head` hook twice. Why does comments need its own call? Get rid of second call and see if that doesn't break anything.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "google analytics" }
Retrieving a list of menu items in an array I am currently am working on a custom theme. In this theme, I have a menu that I registered using `register-nav-menu`, and then I am displaying the menu to my web page using the `wp_nav_menu` function. However, I like to retrieve the list of menu items only (the actual menu item names only that were used in wp-admin area to create the menu, and without any html), and I would like save that list of items to an array (i.e, not display it). So, a psuedo code would look like this $menu_items = get_list_of_items($name_of_menu); // $name_of_menu is the result of register-nav-menu, and get_list_of_items is the psuedo function foreach ($menu_items as $item) { // do something with the item } Is there a way of doing so? Thanks.
wp_get_nav_menu_items would appear to be exactly what you require. It returns an array of menu objects.
stackexchange-wordpress
{ "answer_score": 16, "question_score": 21, "tags": "menus" }
get_post_custom single array Is there a way to return single values only when I run get_post_custom($post_id); it seems that I'm receiving double array, even when there only one value for this meta_key
this is what I've done to achieve this, it will return single dimension array when single results are found, and bi-dimensional array when multiple results are found /* * Get post custom Single (in functions.php) */ function get_post_custom_single($post_id) { $metas = get_post_custom($post_id); foreach($metas as $key => $value) { if(sizeof($value) == 1) { $metas[$key] = $value[0]; } } return $metas; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "php, custom field" }
How to modify wp-includes without messing my wordpress installation? I'm using a Twenty Twelve theme with a child theme. When the screen is shrunk to less than a certain width a responsive menu is toggled. The problem is that this menu's top level pages look the same as nested ones so I want to modify the menu's template. I thought this would be a matter of copying the menu's template to my child-theme but the template file is located in wp-includes (it's nav-menu-template.php I belive). How should I modify it so my changes are not erased when I update wordpress? And also with minimum risk of breaking something
You won't want to modify any files outside of wp-content unless you're alright with them being blown away during an upgrade. The best way to modify what you're talking about is in the styles.css file located in the wp-content/themes/twentytwelve folder. This way you just override the specific styles you're not happy with and don't need to worry about upgrades breaking your code. If you want to get a little more advanced, you can start modifying the functions.php and header.php files which house most of the functionality you'd need to modify. The nav-menu-template.php file you're referring to in wp-includes is just a file that processes in the background and outputs data, the actual visual display is probably in header.php and pulls it's design from styles.css.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "menus, templates" }
Load comments.php template outside the post loop I'm loading a post via ajax and outputting using `$post = get_post( $post_ID );` Is there a way to load the comments.php template after I've output my post? I tried using: global $withcomments; $withcomments = true; comments_template(); But it's not within the loop so it's not loading the template. I'm trying to get my comment form and any current comments to display, just having some difficulties. Any help would be much appreciated!
So apparently this is a big no-go, but I've been able to build my own custom comments form and loop using this code: <?php $args = array( 'post_id' => $post_ID); $comments = get_comments($args); if($comments) : foreach($comments as $comment) :?> <div class="comment"><?php print_r($comment); ?></div> <?php endforeach; endif;?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "comments" }
WooCommerce Checkout page customization I'd like some help with customizing the functionality of my WooCommerce driven site. The link can be found here: < How can I customize the output so that it shows the product images that you have in your cart, but on the checkout page ? Also, as a side note to this question, what files / lines of code might I want to look at if I'd like to add another drop-down to the checkout form. Also, if I'd like to change the wording of "select a state" to be "select a province" ? Thanks in advance for your help, as you guys have always aided me in my web-ventures. Sincerely, Chris Coffin.
To add the product image to the checkout review order page, you want to add the following into your functions.php file of your theme. function my_add_order_review_product_image( $product, $product_obj ) { $image = wp_get_attachment_image( get_post_thumbnail_id( $product_obj->post->ID ), 'shop_thumbnail' ); return $image . $product; } add_filter( 'woocommerce_checkout_product_title', 'my_add_order_review_product_image', 10, 2 ); This is utilizing the filter hook that is present in order reviews file template of WooCommerce.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "customization, plugins" }
Making the Content Editor Box Bigger in 2013 I know that question have been answer, but answer is no more current with wp 3.5.2 (or 3.6) and many plugin, qtranslate first... i dont have the "size of the post box" in Settings > Writing. Yes i can manually extent the box with the lower right triagle, but when saved, it's back to super small 2-3 line in height So the question, how do i change it PERMANANTLY to 30 line in height ?
I write a small plugin to give ability for user to change the edito height in a option of profile page. A sort of back in time to WP < 3.5.2 ## Workflow 1. Create custom field in the profile settings 2. On admin init check if we are in the right page, if so set an hook for the filter `the_editor` 3. In funcion hooken into `the_editor` get the user option and use a regex replace to change height, only if the id of the editor is the right one to prevent plugin interfer with other calls of `wp_editor` ## Edit I've created a better version of the original posted plugin. It's almost the same but is coded in a class and give 2 options for editor height: one for desktops one for mobile devices. The code can be found in **this Gist**. Plugin in quickly tested on WP 3.6 and seems to work. Below a preview of how this plugin let set the options: !enter image description here
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "editor, wysiwyg" }
Why won't the Comprehensive Google Map Plugin load? all. I could use some help troubleshooting a plugin, since the plugin's author hasn't responding to support threads on the plugin page. I'm using the Comprehensive Google Map Plugin to display a map on a page. Or, at least, I'm trying to. When I put the shortcode in a page and publish it, the page gives me a loading spinner that never stops spinning. You can see that here. (The site's still very much a work in progress, so pardon the sloppiness.) A support thread in the WordPress plugin repository from three weeks ago for a similar issue (I'd post a link, but I haven't got enough reputation yet) suggests that the problem might be an HTML error causing a Javascript error, but I'm not sure how to find an error like that, if that's even my issue. If anyone could take a look and suggest solutions, I'd really appreciate it. Thanks so much.
If you check the JavaScript error console, you'll see the plugin is throwing an error: Error: SyntaxError: missing ) after condition Source File: Line: 33, Column: 60 Source Code: tions").val();d=w(d);m=parseFloat(a.fn.jquery);if(1.3>m && m~=1.10)return alert(i.oldJquery),!1;if("undefined"== If you look at the plugin page, you'll that the majority of people are reporting the plugin as broken, and it hasn't been updated for almost a year. It's time to find an alternative plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, jquery, javascript, google maps" }
Include print style sheet How do I properly link a print style sheet? All my styles have been enqueued through functions file. The codex suggested I put the link in the header but this didn't work, is there a core print stylesheet? I tried to create a link in the header but I see any of these styles? I do see the print.css file in the header when I look at the source. /css/print.css" type="text/css" media="print" />
Use `wp_enqueue_style` to add a print stylesheet, note the `media` parameter that lets you make it a print-specific stylesheet: function wpa_print_styles(){ wp_enqueue_style( 'wpa-print-style', get_stylesheet_directory_uri() . '/print-style.css', array(), '20130821', 'print' // print styles only ); } add_action( 'wp_enqueue_scripts', 'wpa_print_styles' );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "css" }
printf, translation and the_author_posts_link() For some reason the following code is not displaying correctly on the frontend of my site - <?php printf( esc_attr__( 'About %s', 'textdomain' ), the_author_posts_link() ); ?> Instead of displaying the translatable string 'About' before the author's name/link, it's displaying it afterwards. I assume this is because I'm using a function in there instead of a variable. Is there a way to make this work or should I completely re-write this?
`the_author_posts_link` "Displays a link to all posts by an author." That is, the function `echo`s content. It does not return the content for use by some other function. You won't be able to use that function, but you should be able to use it as a model for your own function for generating and `return`ing the link instead of `echo`ing it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates, author, front end" }
Having problem in using wordpress with an other language I am using Persian Wordpress but I have a problem. when I want to publish a new post in Persian , I get all Persian letters alternated with question mark -"?" -. My wp-config.php file set the database charset to utf-8 .I installed Persian language to my Wordpress but it didn't fix my problem. you can see my full problem in chergheshab.ir . I also tried to change my collation from phpMyAdmin to utf8_general_ci but it didn't work . thanks a lot !
You should have all your databases utf8_general_ci if you're website uses other than just Latin characters. Can you have a look at your database tables? If you can then have a look at the `wp_posts` table and see if they are `????` or actual characters. Otherwise your posts are saved wrong in the DB which why they are appearing unreadable in your blog. If they do not have utf8_general_ci unicoding try to: * Either create a new database with utf8_general_ci Unicode or try to convert your current DB. Documentation about converting a database. BACKUP if you need to! * Install a clean WordPress via FTP * Make sure your config.php has these settings (which are the default): define('DB_CHARSET', 'utf8'); define('DB_COLLATE', ''); * After installation make sure all your tables are utf8 general_ci (if you can access your database?) * Make sure your theme's index.php is saved with UTF-8 encoding. Give it a try and let me know if this changed anything?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multi language, localization, language" }
Function to Set Product type in Woocommerce I am trying to add a subscription product with custom function in WooCommerce. I am able to add a simple product along with the `post_meta`, but unable to set the `product_type` for that product. Does anyone know the function for saving `product_type` in WooCommerce?
I figured this out, to set the `product_type`, instead of using `update_post_meta()`, you use: > wp_set_object_terms( $productID, 'subscription', 'product_type' );
stackexchange-wordpress
{ "answer_score": 8, "question_score": 3, "tags": "plugins, woocommerce offtopic" }
Fetch post meta data on POST request I have inserted values product-price, name and size in wordpress. The insert code is below function products_save_postdata($post_id) { if (isset ($_POST['price'])) { update_post_meta($post_id, 'price', esc_attr($_POST['price'])); } if (isset ($_POST['product_name'])) { update_post_meta($post_id, 'product_name', esc_attr($_POST['product_name'])); } if (isset ($_POST['size'])) { update_post_meta($post_id, 'size', esc_attr($_POST['size'])); } } How can i fetch this inserted data?
<?php $args = array('post_type'=>'products','posts_per_page'=>10,'number_posts'=>10); $products = get_posts($args); foreach($products as $product) { $productid = $product->ID; echo $producttitle = $product->post_title; echo $productdescription = $product->post_content; echo get_post_meta($productid ,'price', TRUE); echo get_post_meta($productid ,'product_name', TRUE); echo get_post_meta($productid ,'size', TRUE); } ?> if the value is empty it shows null otherwise
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post meta" }
Prohibit saving a post without providing a title How to prevent saving a post without providing a title? Right now it's possible. I want to prevent that. How to achieve this task?
Perhaps these plugins will help you: ## Mandatory fields This plugin is responsible for making certain fields mandatory before publishing any post in wordpress. !enter image description here ## Force Post Title This is simple plugin which forces the users to write POST title in Add New Post page. !enter image description here They both seem to prevent the posting only via JavaScript validation in the backend. If you want to restrict creating posts on the backend side you might want to look into these hooks: * save_post * wp_insert_post
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts" }
Login with email (WP Modal Login) I'm trying to fork this plugin to use the user email to login, as opposed to Username. The plugin is < Is there a nice way to do this, perhaps by a filter to get this plugin to work with email credentials? I've tried using this filter: function custom_login() { $data = array(); $data['user_login'] = sanitize_user( $_REQUEST['username'] ); $data['user_email'] = sanitize_user( $_REQUEST['user_email'] ); $data['user_password'] = sanitize_text_field( $_REQUEST['password'] ); $data['rememberme'] = sanitize_text_field( $_REQUEST['rememberme'] ); $data['user_login'] = sanitize_user( $_REQUEST['user_email'] ); $user = wp_signon( $creds, false ); if ( is_wp_error($user) ) echo $user->get_error_message(); } // run it before the headers and cookies are sent add_action( 'after_setup_theme', 'custom_login' );
I'm using this simple action, and it works like a charm. :) <?php /** Plugin Name: (#111223) User Login with Mail Address */     add_action( 'wp_authenticate', 'wpse111223_login_with_email_address' ); function wpse111223_login_with_email_address( $username ) { $user = get_user_by_email( $username ); if ( ! empty( $user->user_login ) ) $username = $user->user_login; return $username; } It hooks to wp_authenticate and enables email login to the WordPress Authentication system, so it should work with any plugin. I use it successfully with **Login with Ajax** plugin. :) Later-edit: For those who don't know where to put the snippet of code, it should go in your theme's `functions.php` or a custom plugin.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "plugins, login, wp login form" }
Do I actually need to link my theme's style.css in the theme files So I am developing a wordpress theme using a series of LESS files for the CSS. These compile using codekit to a combined and minifed stylesheet that I use for the theme's styling. I understand a wordpress theme must have a style.css which includes the info about the theme in its comments, but is it required to link this style.css in the header.php? Surely I can just have the theme info in it and nothing else and leave it untouched in the theme folder. The stylesheet I actually use can just be called styles.css or main.css or something. can anyone confirm this or give reasons why this might be a bad idea?
I would say: you _should not_ use the `style.css` for the actual production CSS. The reason is simple: minification. You cannot minify the content of the file completely, because WordPress has to read it. In my themes, I use `style.css` just for the headers, and I add a comment, explaining where to find the real CSS, so other developers don’t have to search too long. Example: /* Theme Name: My theme name Version: 2013.08.24 License: MIT Text Domain: t5_theme Domain Path: /lang You will find the real stylesheet in css/default.css. */
stackexchange-wordpress
{ "answer_score": 16, "question_score": 11, "tags": "theme development, themes, css" }
Get only used meta_values this is how I'm getting the meta values: $apart_locations = $wpdb->get_col( "SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'postal_location' ORDER BY meta_value ASC" ); This is how I'm getting the published posts of a custom post type: $apartments = $wpdb->get_col( " SELECT DISTINCT( post_id ) FROM $wpdb->postmeta WHERE meta_key IN( $fields_string ) AND post_id IN ( SELECT ID FROM $wpdb->posts WHERE post_type = 'tvr_apartment' AND post_status = 'publish' ) ORDER BY rand() " ); So my concern here is how can i get the meta_values only from the ones that are used by at least 1 published post? any idea how? -EDIT- I'm trying to Do this because the first query returns metas that are unnused: !enter image description here
I am not sure if I get your question right, and thus don't know if this answer goes into the right direction... Is this what you're trying to achive? $apart_locations = $wpdb->get_col( "SELECT meta_value FROM $wpdb->postmeta AS wppm LEFT JOIN $wpdb->posts AS wpp ON wppm.post_id = wpp.ID WHERE wppm.meta_key = 'postal_location' AND wpp.post_status = 'publish' ORDER BY wppm.meta_value ASC" );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom post types, post meta, get posts, publish" }
Wordpress appends RSS item with unwanted content Wordpress is adding a message to the end of each item in RSS feed that reads "The post [post_name] appeared first on ]site_name]." I want this message to go away. I browsed through a my feed.php files, but couldn't find the code that assembles this message. Where should I look for this?
This text is probably being added to your feed by the "WordPress SEO by Yoast" plugin. In your admin panel menu, go to SEO, RSS. Delete everything in the box labeled "Content to put after each post."
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "rss, feed, plugin wp seo yoast" }
Are .MP3 files with capital letter extensions allowed in [audio] shortcode? In WordPress 3.6, using the new `[audio]` shortcode, I can add a player for an .mp3 file like this: [audio src=" However, if the .mp3 file has capital letters in the extension, it doesn't work: [audio src=" If I specify the format in the shortcode, it still fails, although in a different way: [audio mp3=" Looking at function `wp_audio_shortcode` in "wp-includes/media.php", I can see where this is happening. Is this intentional behavior for WordPress 3.6? Are there any workarounds (other than renaming the file)? Should I file a bug report? # Followup This bug has been fixed in the core for WordPress 3.7.
No, apparently not. Until this behavior is changed in version 3.7 you can add this filter to your theme's `functions.php` file to include additional extensions. Edited: I've updated the filter with better code suggested in the comments. ## Lower case and uppercase extensions function my_custom_audio_extensions( $exts ) { //merge array of upper case extensions with default array return array_merge( $exts, array_map('strtoupper', $exts) ); } add_filter( 'wp_audio_extensions', 'my_custom_audio_extensions' ); ## Lower case, upper case, and first letter capitalized extensions function my_custom_audio_extensions( $exts ) { //merge array of lower case defaults, uppercase and first letter capitalized return array_merge( $exts, array_map('strtoupper', $exts), array_map('ucfirst', $exts)); } add_filter( 'wp_audio_extensions', 'my_custom_audio_extensions' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "shortcode, audio, bug" }
Change default italic from <i> to <em> in admin editor I've noticed that the admin editor by default embeds any italic texts with `<i>` which I intend to use for icon styling. I much more prefer to wrap them with an `<em>`. How would I got about changing this?
Are you sure editor use `<i>` for italics? I'm almost sure it uses `<em>`. However, if you want to be absolutely sure there are no `<i>` in your post content, let editor do what it want and then replace `<i>` with `<em>` before creating/updating posts, hooking `wp_insert_post_data` filter, just like: add_filter('wp_insert_post_data','replace_em', 20, 1); function replace_em( $post_data ) { if ( $post_data['post_content'] != '' ) { $post_data['post_content'] = str_ireplace( array('<i>', '</i>'), array('<em>', '</em>'), $post_data['post_content'] ); } return $post_data; } Even if you insert `<i>` manually, they are replaced with `<em>` on saving.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "admin, editor, content, text" }
Inserting a random number into an array So what im trying to do is make a random offset for 'top comment', at the moment it's working great(with no offset) but I want to randomise the offset so it displays 1 of the top 5 comments by offsetting it. So I was either going to use a range or an array; whichever works best. Everything is ok on the first two lines - I can print and echo it fine, but when it comes to using the variable within my second array it just defaults back to the 0 offset. Any help or advice would be greatly appreciated - code below. $numbers = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5); $random_key = array_rand($numbers, 1); $comments = get_comments(array('orderby' => 'comment_karma', 'number' => 20, 'status' => 'approve', 'offset' => '.random_key.'));
offset parameter of get_comments() function accepts integer values for more information visit this codex page. so your get_comments function call should be as following. $numbers = array(1 => 1, 2 => 2, 3 => 3, 4 => 4, 5 => 5); $random_key = array_rand($numbers, 1); $comments = get_comments(array('orderby' => 'comment_karma', 'number' => 20, 'status' => 'approve', 'offset' => $random_key));
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "array, comments" }
WordPress: Getting "Newer Posts" and "Older Posts" links on a Specialized Page Template I am using a Specialized Page Template to display list of posts. I am using the following code for that: <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'paged' => $paged ); $all_posts = get_posts($args); ?> <?php foreach ( $all_posts as $post ) : setup_postdata( $post ); ?> /* the loop */ <?php endforeach; ?> Now I want to put "Newer Posts" and "Older Posts" links below it. `next_posts_link()` and `previous_posts_link()` prints nothing here. How can I add these two links on this page?
You can achieve this using WP_Query as shown in the following code. To know more information on this visit this page. <?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $the_query = new WP_Query( 'posts_per_page=5&paged=' . $paged ); if ( $the_query->have_posts() ) : // the loop while ( $the_query->have_posts() ) : $the_query->the_post(); the_title(); endwhile; next_posts_link( 'Older Entries', $the_query->max_num_pages ); previous_posts_link( 'Newer Entries' ); // clean up after our query wp_reset_postdata(); endif; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pagination" }
Updating shortlinks from staging Many of the shortlinks on pages of our site are links to our staging site. The current live site started life as the staging version, so I imagine that's why, but I don't know how to fix the issue. Does anyone have any tips as to how to achieve this? **Update** Apologies, this is actually the < shortlinks created and added to the head of pages by Jetpack. I need to know how to clear/update these, to reflect the change of domain (from staging to production). Hope this is now clearer.
There are 2 solutions to your problem: * You can go to the Jetpack menu in your dashboard and disconnect, then reconnect to WordPress.com. It will force an update of your Jetpack settings. * You can contact the Jetpack support team here: < They can update your Jetpack settings for you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin jetpack, shortlink" }
Edit Media - Edit Custom Sized Featured Images When I edit images in the wordpress backend - crop, aspect ratio etc. my featured images don't change. I've tried all combinations of saving (All image sizes, Thumbnail, All sizes except thumbnail). How can I make these changes effect my featured image? This featured image is a custom size using add_image_size() eg. `add_image_size( 'featured', 638, 300, true );`
This could be down to how the featured image is being called as it's possible to pass an array with a custom size, rather than using one of the set image sizes that comes with WP, or indeed a new image size that was added with `add_image_size()` \- what code are you using?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails" }
Using Custom Value Options in PHP I'm currently using a custom field called "Developing" to show whether or not a news story is a developing story. The custom field has a couple of values: a blank option (meaning it is not developing), "Yes," and "Was Developing." This is the code I use to display the word "Developing" in front of a news story title: <?php if (get_meta('developing') != "") { ?>Developing: <?php } ?> While it shows "Developing" when I've hit Yes, it also shows "Developing" when I change the option to "Was Developing." I'm assuming this is because I'm calling up the entire thing and not distinguishing between its options in the coding. Does anyone know if I can even do this? For example, can you have different messages show for each option? Something like using "developing's yes option means show this" instead of just "developing means this" like above? Thank you!
use `get_post_meta($post->ID, 'your key', true);` instead of `get_meta();` compare values like $developing = get_post_meta($post->ID, 'developing', true); if ($developing == 'value') { // value is matched } elseif ($developing == 'value2') { // value 2 is matched } else { // not matched }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Wordpress get number of categories I have a page of multiple categories (mysite.com/?cat=1,2,3,4). My archive template shows the name of the selected category as a heading. Now I have four categories, but only the name of the first shows up. Instead, I'd like to check if more than one category is selected and then show no heading. So, how do I find out how many categories are selected? (-> This needs to work outside the Loop)
This is untested, but I think it should work. Multiple categories will result in the `category__in` query var containing an array of the queried categories- if( isset( $wp_query->query_vars['category__in'] ) && count( $wp_query->query_vars['category__in'] ) > 1 ){ echo 'multiple categories queried'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development" }