INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
preview_post_link for Custom Post Types I've got a custom post type, and I'd like to be able to change the preview link but from what I can tell, the hook for preview_post_link only affects the default post type. Any guidance? Here's what I've been trying. add_filter( 'preview_post_link', 'append_preview_query_vars' ); function append_preview_query_vars( $link, $post ) { if( $post->post_type === "2016program" ) { return $link . "?program_year=2016"; } else { return $link; } }
## Two problems here: **#1** You're missing the `$accepted_args` argument in: add_filter( $tag, $callback_function, $priority, $accepted_args ); Check out the Codex here for more info on that. **#2** Note that `$link . "?program_year=2016"` is problematic, since it gives us this kind of link: /?p=123&preview=true?program_year=2016 But using instead `add_query_arg( [ 'program_year' => '2016' ], $link )` we get the correct form: /?p=123&preview=true&program_year=2016 ## Updated code snippet: Please try this instead (PHP 5.4+): add_filter( 'preview_post_link', function ( $link, \WP_Post $post ) { return '2016program' === $post->post_type ? add_query_arg( [ 'program_year' => '2016' ], $link ) : $link; }, 10, 2 ); // Notice the number of arguments is 2 for $link and $post where we use `add_query_arg()` to append the extra GET parameter to the link.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "filters, previews" }
Add filter menu to admin list of posts (of custom type) to filter posts by custom field values Also the same question as here: Add filter menu to admin list of posts (of custom type) to filter posts by custom field values But need to search by selecting meta_key and searching by meta_value but not exact value. Tried to use %search_string% or _search_string_ didn't helped. Any suggestions? (Need to add LIKE param somewhere)
Just add: $query->query_vars['meta_compare'] = 'LIKE';
stackexchange-wordpress
{ "answer_score": -1, "question_score": 1, "tags": "filters" }
Check if value has changed on save_post Writing a function to send an email to the user on save_post if a taxonomy equals a specific value. However, I only want this to happen when the value is being changed, and not on every save. Is there a way to compare if a value is being updated with a new value versus the same value it already has? function status_save_email( $post_id ) { if ( !wp_is_post_revision($post_id) ) { $slug = 'sessions'; if ( $slug != $_POST['post_type'] ) { return; } $status = get_the_terms( $post_id, 'status_tax' ); if ( $status != null ){ foreach( $status as $state ) { $state_name = $state->name ; }} if ( $state_name == 'Rejected' || $state_name == 'Approved' ){ echo "bingo"; } } }
In the end I checked against and updated a new meta value on each save. $screen = get_current_screen(); if ( $screen->base == 'post' && $screen->post_type == 'sessions') { if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; if ( isset( $_POST['session_status_tax'] ) ) { $status = $_POST['session_status_tax']; } else { $status = ''; } $prev_term = get_post_meta( $post_id, 'prev_term', 'true' ); if ( $status === 'status-approved' && $status !== $prev_term ) { write_post_log($post_id, 'Approved' ); send_email( $post_id, 'Approved' ); } update_post_meta( $post_id, 'prev_term', $status ); } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "save post" }
Get Commentor IP When Marking Comment As Spam What I am trying to do is create a list of IP addresses each time I click Spam on a comment. The only issue I have now is, how do I get the commentors IP address inside this function. This is what I am working with... It ties into the onclick event of the Spam button. add_action('transition_comment_status', 'report_spam', 1); function report_spam($new_status){ if($new_status == 'spam'){ //do something here with IP } }
You are missing 2 parameters in your function `report_spam`. Also the priority should not be 1. Try the code below. add_action('transition_comment_status', 'report_spam', 10, 3); function report_spam($new_status, $old_status, $comment){ if($new_status == 'spam'){ var_dump($comment->comment_author_IP); die; } } I've set `die` so that you can check and manipulate what you want.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, comment form, spam, comments" }
Filter user list that meta_value is empty I am trying to get all users that meta value is empty so i tried many variations and cant get the list of all user that birthday field is empty (not set). $user_query->query_vars['meta_key'] = 'birthday'; $user_query->query_vars['meta_value'] = ''; //or $user_query->query_vars['meta_value'] = Null; $user_query->query_vars['meta_compare'] = '=';
I think the use of `meta_query` is in order: $user_query = new WP_User_Query( array( 'meta_query'=> array( array( 'key'=> 'birthday', 'compare' => 'NOT EXISTS' ) ) ) ); Basically, this looks for all users where the meta key of `birthday` doesn't have a value ie doesn't exist. More info about meta queries in `WP_User_Query` can be found here
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "wp query, users" }
Cloning admin pages like users.php In my project I want to make a new menu position which will be actually a copy of 'Users' page but with some additional filters/modifications. For example as a result I need to have another menu position above users called "Admins" which will show exactly same structured page but with only Admin users. It is for better/easier user experience for my client. My question is how to do this? I know that there are functions like `add_menu_page` but using them like this (`users.php` as identifier): add_menu_page( 'custom menu title', 'custom menu', 'users.php', 'myplugin/myplugin-admin.php', '', plugins_url( 'myplugin/images/icon.png' ), 6 ); results in two menu positions which collapse and expand together, and I wanted them to work independently. I can also show content based on function but I don't know if there is any way to easily output content of whole users.php page?
After some further research I have used WP_List_Table class for this. I had to add buttons and links myself to make it look like users.php but it wasn't much of work.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, add menu page" }
Using Cookie Data For WP_Query Loop I'm trying to retrieve data set in a cookie and use this to run a query. I've set the cookie in functions.php like so; add_action( 'init', 'resultsCookie' ); function resultsCookie() { setcookie( 'your-results', '18,17,11,8,10,27,26', time() + 3600, COOKIEPATH, COOKIE_DOMAIN ); } While I can echo the string, I can't seem to get this functioning within the query; $cookie_array = $_COOKIE["your-results"]; // Test output echo $cookie_array; $sug_args = array( 'post_type' => 'product', 'post__in' => array( $cookie_array ) ); $sug_query = new WP_query ($sug_args); if($sug_query->have_posts()) : while($sug_query->have_posts()) : $sug_query->the_post(); // Run Loop wc_get_template_part( 'content', 'product' ); endwhile; endif; wp_reset_query(); Any ideas?
You need to explode the comma separated string to get the array of IDs. Follow the below code. $cookie_array = $_COOKIE["your-results"]; // Test output echo $cookie_array; $cookie_array = array_map( 'absint', (array) explode(',', $cookie_array) ); $sug_args = array( 'post_type' => 'product', 'post__in' => $cookie_array, ); $sug_query = new WP_query ($sug_args); if( $sug_query->have_posts() ) : while( $sug_query->have_posts() ) : $sug_query->the_post(); // Run Loop wc_get_template_part( 'content', 'product' ); endwhile; endif; wp_reset_query();
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, wp query, woocommerce offtopic, cookies" }
How does WordPress Multisite know that a Plugin is installed? I am running a WP Multisite Network. I am curious to know how WordPress knows that a plugin is installed on a network site: * how does WP know that a plugin is Network Activated? * how does WP know that a plugin is activated at the site level? Does it record this instance in a DB Table somewhere? If so, which table and how is it tagged? Thanks for helping.
You can clearly see the way WordPress loads plugins if you inspect the source code of the file `wp-settings.php`. The function `wp_get_active_and_valid_plugins()` loads plugins for individual sites in the network and for non-Multi-Site installations, while `wp_get_active_network_plugins()` loads network activated plugins when Multi-Site is enabled. The former more or less just calls get_option() to get the `active_plugins` option from the wp_options database table, while the latter uses get_site_option() which is the network-wide version of `get_option()`. The option which has the network enabled plugins is called `active_sitewide_plugins`.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "plugins, multisite" }
Display page contain in index.php file I use following code to display page in a index.php file of template but doesn't show page content. <?php $parent_page_content = get_the_content(1677);///my_page_id echo $parent_page_content; ?>
get_the_content( $more_link_text, $stripteaser ) `get_the_content` does not take a post ID as a parameter, it always refers to the current post. Also, don't use magic numbers or hardcode post IDs into your theme, it will break after an import/export or migration. Instead use `get_page_by_title`, which is not as bad: // get the post $post = get_page_by_title('page or post title', OBJECT, 'post' ); // filter its content $content = apply_filter('the_content', $post->post_content ); // display it echo $content;
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "pages" }
Facebook / LinkedIn share page - https opengraph issues I have added the Open Graph meta data to my **functions.php** : function insert_fb_in_head() { global $post; if ( !is_singular()) return; echo '<meta property="fb:admins" content="PAGE_ID"/>'; echo '<meta property="og:title" content="' . get_the_title() . '"/>'; echo '<meta property="og:type" content="article"/>'; echo '<meta property="og:url" content="' . get_permalink() . '"/>'; echo '<meta property="og:site_name" content="SITE_TITLE"/>'; echo '<meta property="og:image" content="' . $default_image . '"/>'; } add_action( 'wp_head', 'insert_fb_in_head', 5 ); However when pasting from HTTPS, it does not fetch the OG data. Sharing from HTTP works perfectly fine. I also tried adding: og:image:secure_url Didn't work either. !HTTP vs HTTPS LinkedIn Share
I used the Open Graph Debugger: < Result: Inferred Property The... property should be explicitly provided, even if a value can be inferred from other tags. So all I had to do: <meta property="og:..." content=" <meta property="og:..." content=" /> That extra space between **" />** was the fix. Weird. Also remember LinkedIn caches the data for **7 days** , so check later on the week if fully resolved.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "facebook, https" }
Updating plugins asks for FTP information, why? (this is a new one) First off, this has nothing to do with permissions, I already checked that. So please don't mark this as a duplicate. Any time I try to update a plugin, I get this dialog: !enter image description here I went overboard and allowed all permissions (-rw-rw-rw-) on all files, and _still_ the plugins won't update without FTP. And SFTP is not an option, as I'm using ssh keys on this server (no passwords allowed). I'm running WP on nginx and php5-fpm. What else should I try to do?
Figured it out. Apparently WordPress is a bit dumb, and even if your files are owned by user `abc` and group `www-data` (`abc:www-data`) and are all group-writable, WordPress still won't do the easy update method unless the files are actually owned by `www-data:www-data`. It doesn't even bother checking the group permissions.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, updates, permissions" }
Woocommerce product listing design issues In my design the every product is listing like <div class="col-md-3 special-products-grid text-center"> <a class="brand-name" href="single-page.html"><img src="images/b2.jpg" title="name" /></a> <a class="product-here" href="single-page.html"><img src="images/p2.jpg" title="product-name" /></a> <h4><a href="single-page.html">Line Link 67009</a></h4> <a class="product-btn" href="single-page.html"><span>109.90$</span><small>GET NOW</small><label> </label></a> </div> while in woocommerce plugin the product is listing in ul and li fashion how i fixed this issue because i have set the css on div while in woocommerce shop page it listing in ul.
Nasir, you can inherit the woo-commerce template files into your current theme and integrate your html, here you can find the woo theme Integration guide <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
Wordpress Failed to Login (DB Error) is there anyone experience how to fix DB Error on WordPress (switch back to default theme and reset all plugins from FTP) but still cannot login). This is the erro I got: WordPress database error: [Got error -1 from storage engine] UPDATE `cm_options` SET `option_value` = '1436261132.2179160118103027343750' WHERE `option_name` = '_transient_doing_cron' When click the login in wp form is nothing happened. Thanks,
Error -1 is fairly broad, but has a few common causes: 1. A full disk 2. Memory or resource issues on the server (check mysql logs) 3. Database Corruption (run checks on the database tables) If the issue winds up being database corruption, you will want to follow the repair procedures for the storage engine used for the corrupted tables. If all else fails, roll to a backup.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "database, wp login form" }
Registered access area I want to do in my wordpress site appears wp-login.php for guests in all site, not just in an article or something. How i could do that? Wich files i should modify? Registered users and admin users can see the site, but guests not. Thanks!
Ok i solved with this way: // Redirect guest users function login_redirect() { global $pagenow; // If user is not loged in and not in the login page if(!is_user_logged_in() && $pagenow != 'wp-login.php') auth_redirect(); } add_action( 'wp', 'login_redirect' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, registered" }
WordPress Permalink feature alternative I'm trying to prefix my permalinks for some backend logic to emulate posts on Multisite. I have used the `post_link` filter but unfortunately it didn't meet my needs as it doesn't prefix the permalink for custom post types (annoyingly!) Does anyone know of a method that I can prefix custom post type permalinks with? For example `www.domain.com/PREFIX/post-slug-here/`
For custom post types, use the `post_type_link` filter just a you would use the `post_link` filter for `post` post type posts
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "permalinks, filters" }
How can you change default color scheme in a Twenty Fifteen child theme? Right now I am editing a Twenty Fifteen Child theme (Five Beers to be exact) and I'm wondering if there is a way I can add my own color scheme to the customizer and make it the default color scheme. This is the code that I've been using to add a color scheme to the list, and I sourced it from here: add_filter('twentyfifteen_color_schemes', 'my_custom_color_schemes'); function my_custom_color_schemes( $schemes ) { $schemes['maroon'] = array( 'label' => __( 'Maroon', 'twentyfifteen' ), 'colors' => array( '#f1f1f1', '#C32148', '#ffffff', '#333333', '#333333', '#f7f7f7', ), ); return $schemes; } anyone have any ideas?
I would expect that if you add a new filter with a higher priority it gets added to the existing color schemes: add_filter( 'twentyfifteen_color_schemes', 'wpse193782_custom_color_schemes', 99 ); function wpse193782_custom_color_schemes( $schemes ) { $schemes['default'] = array( 'label' => __( 'Colors by Kat', 'twentyfifteen' ), 'colors' => array( '#f1f1f1', '#C32148', '#ffffff', '#333333', '#333333', '#f7f7f7', ), ); return $schemes; } **Edited my answer.** By (re)naming the scheme `['default']` your own color scheme replaces the default color scheme.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "child theme, theme customizer, theme twenty fifteen" }
How do I create an archive page for standard posts? I've been tasked with creating a portfolio website for a client who also wants a blog. **What I've Done Thus Far:** I’ve created a custom post type to separate the portfolio work from the blog posts and created a `WP_Query` to display them on my `front-page.php`. **The Problem:** Now that my `front-page.php` displays my custom post type (and not my WordPress' builtin posts), I'm not sure how to navigate to my blog archive. What template do I use to create said archive (i.e. `index.php`, `home.php`, `archive.php`, etc) and would I navigate to it?
Create a template with a WP_Query to get posts with post type "post" then create a page and assign that template to that page. Templates: < Query by post type: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "custom post types, posts, wp query, theme development, menus" }
Change WordPress Resource URL I have recently finished developing my latest WordPress theme for my own site and as usual I was going to use maxcdn and w3tc to make it faster! However my Hosting company have started up their own cdn service and I have got 3 months free to test it out! However it is not as easy to set up as Maxcdn and have been told that I need to change the resource url to use cdn url and serve my images, css and js files. I have added all my css and js files in my function.php file like so... wp_enqueue_style('BrumWebEngineer-style', get_stylesheet_uri()); wp_enqueue_style('BrumWebEngineer-core', get_template_directory_uri() . '/css/core.css'); Naturally I cannot replace the get_template_diretory_uri with the cdn url so am wondering how I can go about this. Many thanks.
To dinamically change the stylesheet and template URI you can use `stylesheet_uri` filter and `template_directory_uri` filter. For example: add_filter( 'stylesheet_uri', function( $stylesheet_uri ) { $stylesheet_uri = 'your new stylesheet URI here'; return $stylesheet_uri; } ); But, as you are using W3TC, you can configure that change in the plugin itself (Generic Mirror and Self-hosted CDN options), even you can configure pushing files automatically if the CDN service support it.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, cdn" }
Add class="media_type" when media is inserted into editor I am looking for a way to edit the link that get inserted in the editor when the user choose to add a media. The goal would be to add a class with the media type (pdf) in the link. I know how to get the mime type but I am not sure which hook to use to retrieve the link before it gets inserted. Could you point me in the right direction? Thanks!
So thanks to @amritanshu and @wycks github's code, here is the solution for those in need to add a class with the media type to the attachment url before it gets inserted in the editor : if ( ! function_exists( 'epc_add_class_pdf' ) ) : function epc_add_class_pdf( $html, $id ) { $attachment = get_post( $id ); $mime_type = $attachment->post_mime_type; // I only needed PDF but you can use whatever mime_type you need if ( $mime_type == 'application/pdf' ) { $src = wp_get_attachment_url( $id ); $html = '<a class="pdf" href="'. $src .'">'. $attachment->post_title .'</a>'; } return $html; } endif; add_filter('media_send_to_editor', 'epc_add_class_pdf', 20, 3);
stackexchange-wordpress
{ "answer_score": 3, "question_score": 5, "tags": "media library, editor" }
Database query works fine outside Wordpress This is my code <?php global $wpdb; $rows = $wpdb->get_results("SELECT `submit_time` AS 'Submitted', max( if( `field_name` = 'Salutation', `field_value` , NULL ) ) AS 'Salutation', max( if( `field_name` = 'First Name', `field_value` , NULL ) ) AS 'First Name', max( if( `field_name` = 'Last Name', `field_value` , NULL ) ) AS 'Last Name', max( if( `field_name` = 'Title', `field_value` , NULL ) ) AS 'Title' FROM `wp_cf7dbplugin_submits` WHERE `form_name` = 'Sign Up' GROUP BY `submit_time` ORDER BY `submit_time` DESC LIMIT 0 , 100 "); foreach($rows as $a){ echo $a->field_value;//field value is col name } $wpdb->print_error(); ?> What I am doing wrong here ?
After struggling with different functions , I figure out `$wpdb->get_row()` and `$wpdb->get_var()` The first one returns rows into an associative array or numerical array , depends on the second argument in `$wpdb->get_row('query',ARRAY_A or ARRAY_N or OBJEECT)` and the second one that I used to solve my problem return only one variable from particular table. e.g, <?php $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users" ); echo "<p>User count is {$user_count}</p>"; ?> Reference link
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, mysql, wpdb" }
hook filter after the_content on a specific page I've made a function to hook after the_content. This is only working on certain pages/posts. It's working on the default template but not on my custom one's. function insertFootNote($content) { $content.= "<div>"; $content.="additional content"; $content.= "</div>"; return $content; } add_filter ('the_content', 'insertCpontent'); In my custom page template I haven the following code <?php if(have_posts()): ?> <?php get_template_part( 'part', 'addressbook' ); ?> <?php endif; ?> in the template('part-addressbook.php) I have the following. echo '<div class="category-description"><p>'.get_the_content().'</p></div>'; On this template part the hook is not working although i'm using the_content/get_the_content function Why does the hook does not work in this case?
get_the_content do not apply the_content filter. You have to apply it after receiving contents like following <?php apply_filters('the_content',get_the_content( $more_link_text, $stripteaser, $more_file )) ?> It is also detailed at the bottom of codex page
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, filters, hooks" }
Are all hooks/functions tied to Kses meant for sanitization? I'm currently learning WordPress hooks and am delving into core to see what's happening in there. I noticed there are filters in wp-includes/default-filters.php with PHP comments about Kses. I wasn't sure what Kses meant until I found wp_kses in the Codex. The notes on this page says: > KSES is a recursive acronym which stands for “KSES Strips Evil Scripts". So then do I assume anything I find in core with either kses in the code or the PHP comments has to do with data sanitization? Just trying to understand general patterns in WordPress core. Thanks! :-)
> ... anything I find in core with either kses in the code or the PHP comments has to do with data sanitization? It would have to do with the functions that sanitize data or with data that needs to be sanitized, yes. That is the primary reason for the KSES code, which, if you look it over, is pretty resource intensive. You wouldn't want to use it unnecessarily.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "php, hooks, core, sanitization" }
Automatic Logout on from another active session I have a made **application over Wordpress** for premium user where user can see page **after logging** into his account. but there is issue that same user can login form **multiple computer** , so I want to make function for the user session, when user login in Wordpress then **expires all other sessions** , By this way I can prevent miss use of my Wordpress application. I want a function that would make only **one current active session**.
Answer has been updated because don't need to write function, only use `wp_destroy_all_other_sessions` function with `init`like this add_action('init', 'wp_destroy_all_other_sessions'); Developed its plugin and publish on WordPress Download here :One Active session
stackexchange-wordpress
{ "answer_score": 7, "question_score": 6, "tags": "functions" }
Hide posts belongs to few categories in homepage Currently I am using all the latest posts are displaying in the homepage settings. But now I need to hide few specific categories to be displayed in the homepage. All the post belongs to those specific categories should not display in the homepage. Anyone have an idea how should I do that ? **Edited:** I am using following code to retrieve posts to display in the homepage, if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; $args = array( 'paged' => $paged ); query_posts( $args ); if (have_posts()) : while (have_posts()) : the_post();
You can do this with `pre_get_posts`. This hook is called after the query variable object is created, but before the actual query is run. For excluding **category id** `32` and `39` from homepage, you can setup a function like this. function wpse_exclude_categories( $query ) { if ( is_admin() ) return; if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'cat', '-32,-39' ); } } add_action( 'pre_get_posts', 'wpse_exclude_categories', 1 ); **EDIT** Although I would strongly recommend you to use `WP_Query`. But you can change your code to exclude category posts with `query_posts`. $args = array( 'cat' => '-32,-33', 'paged' => $paged );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts, categories, homepage" }
customize taxonomy Page is there a solution to customize taxonomy page and make it like categories page with a Title h1 and customize Sidebar? this is my taxonomy code : register_taxonomy('director', 'post', array( 'hierarchical' => false, 'label' => 'Realisateur', 'query_var' => true, 'rewrite' => $rewrite2));
This depends on how your theme handles Taxonomy pages. If it e.g. has a `category.php` that does stuff different than `taxonomy.php` or `archive.php` this is the reason. Have a look here to see how the template hierarchy works.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy" }
Modifying lightbox plugin to allow for quoting, Does this exist? I've been searching online for a plugin to use with my website that would allow the the user to click on an image in a foogallery image gallery and then have the image open in a fullscreen lightbox. This itself is easy enough, but I would also like the user to be able to be able to click a toggle button and have a quote form that once filled and submitted would be sent to my email appear in the bottom third of the page. Does anyone know of a plugin that allows this or that can be modified or am I out of luck? below is a mock up of what I'd like. !Mockup Any help at all would be much appreciated.
I am afraid there is no such plugin with the exact functionality you are looking for but you can try one of these plugins link to meet your requirements.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, plugin development, lightbox" }
Display Taxonomies in loop with template args I want to display the taxonomies within the loop but with customized template. Here is my code: if ( have_posts() ) { while ( have_posts() ) { the_post(); $args = array( 'template' => '%s %l', 'term_template' => '%2$s', ); the_taxonomies($args); The post is in the two categories: "Neues" and "Zweite". This code shows the post with the taxonomies like this: "Kategorien **Neues** und **Zweite** " how can I change the output like this: " **Neues** , **Zweite** " without the string "Kategorien" and another seperator "und"? I tried the $arg = 'sep' => ', ' but this changes nothing. Thx for help!
The simplest solution: echo get_the_category_list( ', ' ); Following your way: Change your `$args` like so: $args = array( 'template' => '%2$l', 'term_template' => '%2$s', ); And then, add this to your `functions.php` file ( **this will affect all`%l` markers!**); add_filter( 'wp_sprintf_l', function($templates) { // $templates['between_last_two'] = sprintf( __('%s, and %s'), '', '' ); // $templates['between_only_two'] = sprintf( __('%s and %s'), '', '' ); $templates['between_last_two'] = sprintf( '%s, %s', '', '' ); $templates['between_only_two'] = sprintf( '%s, %s', '', '' ); return $templates; });
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, loop, templates, taxonomy" }
Variables in post title How can I make my post title dynamic? Let's say I'm trying to make a post with this title: Today is [day]/[month]/[year] [day] should be parsed into a php code that will retrieve the current day, and the same idea for [month] and [year]
Just use the `the_title` filter to hook into the title content and work with that. add_filter( 'the_title', function( $title ) { // Manipulate the $title as you want and then return that. // You can add test conditions such as 'is_main_query' // ( return $title; } );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "filters, title" }
why update option is not working? I have following code which is not working: var_dump($resp['status']); //output: 'status' => string 'yes' (length=3) update_option('acp_cf_settings' , array('acp_cf_status'=>$resp['status'])); update_option('acp_cf_settings' , array('acp_cf_log'=>$resp['log'])); $options = get_option('acp_cf_settings'); $resp['status'] = $options['acp_cf_status']; var_dump($resp['status']); //output: 'status' => null Here $resp is an array and 'acp_cf_log' setting is updated but 'acp_cf_status' is not updating, so where I am doing mistake ? thanks
update_option('acp_cf_settings' , array('acp_cf_status'=>$resp['status'])); update_option('acp_cf_settings' , array('acp_cf_log'=>$resp['log'])); You are overwriting the setting. After the second `update_option` call there is no `acp_cf_status` key anymore for the array variable, just the `acp_cf_log`. Just to be clear, you would need something like this: update_option( 'acp_cf_settings', array( 'acp_cf_status' => $resp['status'], 'acp_cf_log' => $resp['log'], ) );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development" }
early enqueueing javascript file in page template, not in functions.php Is it at all possible to enqueue javascript file early on page template file? I want to use this way of including scripts to keep my structure clean (so each page template has its own styling and scripts in it). I don't want to use the conditionals inside functions.php. I don't want to change functions.php. I only want to modify template file. I can enqueue the script no problem, but it is always added at the end of the page, and I need this script to be available upfront (before some of the HTML is displayed - preferrably before ANY of the HTML is displayed).
Short Answer: Yes, but... Just make sure your call to `wp enqueue script` is before the call to `get_header()`. The problem is that when you're in a later part of your template the header including the script is already sent to the browser so you can't change it any more. While this is possible I'd still encourage you to reconsider and put this in the `functions.php` or a simple plugin. Enqueueing scripts is application logic and therefore shouldn't be in a template.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "javascript, wp enqueue script" }
Get current title of archive.php I want to get current title at file `archive.php` My code : if ( is_category() ){ echo "CATEGORY"; } else if( is_tag() ){ echo "TAGS"; } else if( is_author() ){ echo "AUTHOR"; } else if( is_tax() ){ echo "TAXONOMY"; } else { echo "ARCHIVE"; } Is there a way to simplify this ? I try this, but didn't work: if ( is_post_type_archive() ) { post_type_archive_title(); }
There was a new function introduced in Wordpress 4.1 called `the_archive_title()` which does just that. You can simply add `the_archive_title()` in your archive page. If you need to filter the output, see my answer here on how to accomplish that
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "archives, archive template, wp get archives" }
How do I change the "href" link that corresponds with an "li class" statement? Using Firebug I can see the statement - `<li class="cat-item cat-item-72143">` and below that is the - `<a href=" I would like to change the link with changing anything else. Can anyone tell me where I can do this? All I can find is the css files, I can't find where that link lives. Thanks!
I am guessing that you are looking at code generated by `wp_list_categories()` based on the class names, but I can't say for sure. If that is the case, then the link is probably generated here%20\)%20.%20'%22%20';): $link = '<a href="' . esc_url( get_term_link( $category ) ) . '" '; Meaning that you could probably alter it with this filter: $termlink = apply_filters( 'category_link', $termlink, $term->term_id ); Proof of concept: function alter_category_link($termlink) { return 'abcdefg'; } add_filter( 'category_link', 'alter_category_link'); wp_list_categories(); Alter the link to what, I have no idea. You don't specify.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "links" }
Why user_pass column in wp_users table is varchar(64) while working on a project, I found that "user_pass" column in "wp_users" table is varchar(64). WordPress always stores user password in md5 which is a 32 char ASCII string. So why not store it in char(32) with ascii collation. I am asking because I am working on a table that stores user password. Is there any other advantage of using varchar(64).
It is because of different encrypted algorithm. Sometimes users will override the MD5, which is the default algorithm, and add their own, which might need a little longer length to store the password. Take a look at the Q&A's »What data type to use for hashed password field and what length?«, having detailed information about hashes and their length, at Stackoverflow for reference.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "database, customization" }
Move both sidebars more to their sides this is the link to my website < I want to move both the sidebars more to their sides of the page because as you can see, they each leave a considerable amount of space on their sides. Also after moving the sidebars, i want to make the content area wider. So can anybody tell me the css for this? Help is greatly appreciated. Thank you.
!Your Complete website has a max width of 1024 So your main Container the part with the content area and sidebar goes to a max width of 1024px. if you increase it then the sidebars will stay the same width and the extra width goes to your content area. Now how do you do this: in you style.css on line 470 this part is defined and you can edit it there. but remember this could break your site if you go overboard with the widening. further if you just want the container to widen and not the header, footer et al. then just add this css .container {max-width:1170px!important;} the `!important` will make sure this style is used. You can also remove the `max-width:1024px;` bit and see the website as below. !full width website
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Integrate Algolia to WordPress site Algol released this on their website: < Which is supposed to allow us to integrate it to a wordpress site. However, I don't understand how am I supposed to do it. Should I just zip the algoliaplugin.php and add it as a regular plugin ? As anyone ever tried to implement it ?
This is just a normal plugin. You can install it by doing the following: * On the Github Page click "Download Zip" button on the right side. * On your WordPress admin panel navigation to Plugins * Click "Add New" button at the top of the page which will take you to the "Add Plugins" page. * Click "Upload Plugin" button at the top which will allow you to upload and install the entire zip file as a plugin. ( WordPress will unpackage it for you ) After that you will be prompted to activate the plugin, if not you can go to Plugins page and manually activate the plugin. Simple as that! Unfortunately, I can't say I've ever implemented this on any of my sites but it looks like they have decent documentation on how to use it. Specific questions regarding the plugin would probably be better suited to the developers themselves @ the support section.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, search" }
No duplicate tags by category I have script to show list tags from category and works very well. <ul class="inline-list"> <?php query_posts('category_name=lain-lain'); if (have_posts()) : while (have_posts()) : the_post(); if( get_the_tag_list() ){ echo $posttags = get_the_tag_list('<li>','</li><li>','</li>'); } endwhile; endif; wp_reset_query(); ?> </ul> It's possible to make no duplicate of tags and limit only 10 tags? Please help Thank you
Finally! just install this plugin < then insert this script to theme `<?php c2c_linkify_tags('24, 9, 33'); ?>` and done!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "query posts, tags" }
Custom setting field value not working inside add_action init hook I have added custom setting options page under WordPress settings and those are working perfectly. I have tested their values also. But when I am using those values inside function file within add_action init hook to perform something on form submission, those values are returning as null. Everything is working except those values return as null. A few examples will really help me! Thanks in advance :) add_action('init', 'myFunc'); function myFunc(){ $myoptions = get_option( 'custom_option' ); $trueorfalse = $myoptions['my_swicth']; $alertemail = $myoptions['alert_email']; // both working outside if( 1 == $trueorfalse && '[email protected]' == $alertemail ){ //do something } }
I found the answer. Problem was I was retrieving those setting option values outside the if statement `if(isset($_POST['formvalue'])){ }` and using them inside it. For that reason values were actually not pulled from database.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "settings api, options, init" }
WP-Admin gives 403 Forbidden after login on CentOS 7 I've setup a brand new CentOS 7 VPS; everything configured by me. LAMP installation and the Apache virtual host configurations are all done. I've checked them before installing Wordpress and the HTML sites were being showed as well as the PHP info and everything else. After that I went on to setup Wordpress as usual. Then I tried to log-in(the log-in page got loaded successfully) but the log-in page directed me to an error message of `403 Forbidden: You don't have permission to access /wp-admin/ on this server.` What seems to be the issue? I've a separate user than `root` managing the VPS whom also has root privileges and it also has ownership on the Wordpress files. Also the files and folder all have 755 as their permissions. Is this a `.htaccess` issue? A detailed explanation would be much appreciated. Thanks. P.S. Also my firewall is not yet installed
Add this in your .htaccess file at website root folder. If you deleted it then create it again and paste this. DirectoryIndex index.html index.php # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ## EDIT Looks like you have issue with `DirectoryIndex`. In your `httpd.conf` search for `DirectoryIndex` and make sure you add index.php in it. Or in your virtual host configuration. Like this. DirectoryIndex index.html index.htm index.php
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "customization, vps" }
Open 'View Page' Button in Editor in new Tab I know it sounds like a Basic Question and I did google first. Google lead me to edit /wp-admin/edit-form-advanced.php to put target='_blank' there. I did that, but this doesn't seem to affect the 'view page' button on the top of the edit page site. I want it to open in a new tab every time. In what file/where can I find that button? Can you give advice on how to systematically search such a location for the future? What is the proper way of doing that and why. Thanks for letting me know
Firstly it is best to not edit your wordpress core files inside wp-admin but rather modify them with filters/actions and hooks. Check the wordpress codex to see all the filters you could use. Here is the code for a filter that you can put into your theme functions file (/wp-content/themes/{ _the-theme-you-are-using_ }/functions.php) to make the view post use `target="_blank"` function my_get_sample_permalink_html($a){ return preg_replace("/<span id='view-post-btn'><a/","<span id='view-post-btn'><a target='_blank'",$a); } add_filter('get_sample_permalink_html','my_get_sample_permalink_html');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "editor, buttons" }
Execute a function when admin changes the user role How can I execute a function, when admin changes the user role of a user? I have two user roles: one is _agent_ and the other one is _client_ . My need is that when admin changes the user role of _client_ to _agent_ , I need to execute a specific function. In this function I need to get the all content and meta fields of user by getting the _user id_.
You can use the `set_user_role` hook, that will only fire when the user role changes: add_action( 'set_user_role', function( $user_id, $role, $old_roles ) { // Your code ... }, 10, 3 ); If you want to restrict this to a profile update, you can use: add_action( 'set_user_role', function( $user_id ) { add_action( 'profile_update', function( $user_id ) { // Your code here ... } ); } );
stackexchange-wordpress
{ "answer_score": 15, "question_score": 9, "tags": "users, hooks, user roles" }
How to intercept a 404 error I'd like to intercept 404 errors and do some things before to show the 404 error page. How can intercept the 404 error?
As was mentioned in a comment, `template_redirect` would be an appropriate hook for intercepting a 404 before the template is loaded. function wpd_do_stuff_on_404(){ if( is_404() ){ // do stuff } } add_action( 'template_redirect', 'wpd_do_stuff_on_404' ); Refer to the Action Reference for the general order of actions on the front end. The main query runs between the `posts_selection` and `wp` actions, so that is the earliest you can determine that a request is a 404. The template is then loaded after `template_redirect`, so it's too late to set headers after that point.
stackexchange-wordpress
{ "answer_score": 23, "question_score": 11, "tags": "hooks, 404 error" }
Only display post if published in last 24 hours? All I'm trying to do here is a simple custom loop using WP_Query to display posts if they are published in the last 24 hours; otherwise, a message appears telling the user to check back soon for fresh posts. I'm trying to use the date_query parameter in my arguments but I'm getting unexpected results...at first it will work, but if I check the page in a few minutes, its as if it reset itself... my loop is set up below: $args = array( 'post_type' => 'surf_reports', 'posts_per_page' => '1', 'category_name' => $cat (this is pulled dynamically in my template), 'date_query' => array( 'before' => strtotime('-24 hours') ) ); And then obviously below there would be a loop, I'm not going to share that bc its standard and I believe unrelated to the issue.
As birgire said date query is an array of arrays May be this solves your problemo. $args = array( 'post_type' => 'surf_reports', 'posts_per_page' => '1', 'category_name' => $cat (this is pulled dynamically in my template), 'date_query' => array( array( 'after' => '24 hours ago' ) ) );
stackexchange-wordpress
{ "answer_score": 6, "question_score": 0, "tags": "wp query, loop, date query" }
How can I make all post image uploads have data-width and data-height attributes automatically by default? Right now all my images automatically have width= and height= when someone adds an image to a blog post. But what if I also want every image to have a data-width= and data-height= and have it equal to what ever the size of the image actually is? Is this possible? I want to use this: < on a website but it seems to need those attributes and it won't work if I have to manually add them to each image for every blog post.
Yes you can. See my working fiddle here: < 1. You need to add an id. example: `<img class="img" id="imageid".....` 2. Delete all atribute "data-width" and "data-height". because it will added automatically. 3. Add this javascript: (you may change the '$' to 'jQuery' if doesn't work with your theme) <script> var img = document.getElementById('imageid'); var width = img.naturalWidth; var height = img.naturalHeight; $( document ).ready(function() { $('div.aspectRatioPlaceholder').find('*').attr('data-width', width); $('div.aspectRatioPlaceholder').find('*').attr('data-height', height); }); </script> Better is using javascript like example above. But if you want to process with php. you can modify your themes/plugin using this: <?php list($width, $height) = getimagesize("image URL here"); ?> it will produce $width as real image width, $height as real image height. Good luck!
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "images, customization" }
Shortcode not working after move wordpress website files After I migrate the existing wordpress website files in public_html, the all new plugins installed, there shorcode are not working anymore on any pages. Here's the page that I put a shortcode from newly installed plugin < How to fix this?
On the page it shows as `[vfb id=’1′]` But, when I view source code, it shows as `[vfb id=&#8217;1&#8242;]` Look again at the code on the actual page - one mark is a right single quotation mark (8217) and the other character is called a 'prime' (8242). Try removing the punctuation marks so it's just `[vfb id=1]` (best to use 'Text' view in editor window for this).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, shortcode" }
How to add show/hide in navigation setting for pages I'd like to add a checkbox for each page's edit page that decides whether or not that page shows up in navigation. How can I achieve something like that in WordPress? Thank you!
You can use the exclude pages plugin. If you activate this plugin, then on each page you find a checkbox with: **Include this page in lists of pages**. If you uncheck it, the page is not shown in your navigation.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "navigation" }
Public and Private Keys are Incorrect for user For some time, I'm getting the error `Public and Private keys incorrect for wp-user` when I try to update a plug-in. I've a CentOS 7 VPS setup with a LAMP stack. I've installed and configured my Wordpress installation which works fine except that I can't update plug-ins or make image uploads via the Wordpress control panel. I let Wordpress access to my server using SSH. I've followed this tutorial to do so. Basically there is a specific user in my system created for this task(making Wordpress connect via SSH) and it has the SSH keys. According to the tutorial, the permissions of various files are all okay(I've double-checked) but nevertheless Wordpress does not perform the operation. What other configuration do I need? Some other information: * the user for the Wordpress SSH operation has a password so it can log-in via Ssh and it's specifically allowed in `ssh_config`
I solved it! Finally after a lot of frustrating days. In the tutorial page, deep down in the comments, someone suggested removing/commenting the following line: define('FTP_PRIKEY','/home/wp-user/'); I did this and immediately the error message disappeared and things started getting updated.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "ssh" }
Website access with http and https I have a WordPress website which is hosted on an Apache Xampp Server, Windows 2012 Server R2. I have put SSL on it and I have added ` as the `siteurl` in Settings. I can access the home page of the website with both ` and ` but I can not access other pages like: * < * < * < Although, all these are accessible using `https`. How can I make them accessible with both `http` and `https`?
The reason that this is happening is that WordPress will always use the 'siteurl' whenever you navigate past the home page. AFAIK there is no way around this to make the pages accessible from multiple urls. If you only want the ssl on certain pages, there are plugins for that. Besides, if you've paid for the ssl on the site why would you want to make it optional for visitors?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "ssl, https, xampp" }
Starting fresh on a blank "theme" So, I have been working on a wordpress website for awhile and learned lots of new things. I used a really nice theme with lots of features. However over time, I found myself not using any of those features and came up with my own. I even customized the original theme look and feel and there is no original theme look or features on the site any more. So, I decide to delete the theme and start fresh with a blank "canvas". Of course I have all the custom php files, js, css that I will simply apply. What is the best way to start with a blank "theme"? Thanks!
Now that you have mastered modifying a Wordpress Theme you are ready to create your own. There are many ways to go about this, and it's up to you to figure out what is best for you. Personally, I like to use a Wordpress Theme framework. My favorite is called Sage (formerly known as Roots). There are other Wordpress Theme Frameworks such as Genisis, Redux, and Underscores. The reason I like Sage is that is very extensible and allows the use of modern development tools (Composer, Ansible, Vagrant, Capistrano, etc.) to create the theme. Check it out: Roots.io
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "themes" }
Why would a Wordpress site go into maintenance mode without me doing anything? This morning, my Wordpress site went into maintenance mode without me having updated anything, and stayed there for about 10 minutes. What could have caused this? I have automatic security updates turned on, could it be that?
The short answer is yes. Wordpress does go into maintenance mode when updates are are installed. You have nothing to worry about. This is default behavior. I do know that there are sometimes issues where Wordpress gets stuck in maintenance mode after updates, but if you don't experence such issues, you are good to go :-)
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "updates, maintenance, automatic updates" }
Display posts by tag I'm trying to display a list of posts by tag within a post. I've cobbled together the following code which I wanted to use in a shortcode, but I'm getting nothing displayed… $args = array( 'tag' => 'my-tag' ); $query = new WP_Query( $args ); if ( $query->have_posts() ) { while ( $query->have_posts() ) { $query->the_post(); $query->get_template_part( 'entry-summary' ); } } get_template_part( 'nav', 'below' ); I've tried using this within the loop using a short code and after the loop to test without success. I'm sure I'm missing something obvious!
Did you try without `$query->` in front of `get_template_part()` ?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, tags" }
X-Axis of Site is Messed Up Because it is in Hebrew One of my client's sites are in Hebrew which is a right-to-left language. I'm using the MH Newsdesk Lite theme found on wordpress.org . The theme is using a **core** wordpress generated class `.screen-reader-text{}` to display the search form with `get_search_form()`. The issue is there's text, specifically "חפס", overflowing off the page on the left. I believe this is due to the fact that it's being displayed in rtl language. I want to make it so the homepage (And possibly some of the other pages and posts, too), _**never**_ scroll to the x-axis. What is the best practice for theme developers and users of these theme to use `.screen-reader-text{}` while maintaining accessibility and not messing up the display (like the page scrolling horizontally in my case)? Here are some links I've found that are relevant: < <
It is due to css: Check this(Line # 314 style.css): .search-form .screen-reader-text { left: -9999px; overflow: hidden; position: absolute; } Remove the left margin then it works fine. It is on sidebar search form. Sorry for English. Thanks
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "themes, css, language" }
Control what custom posts a user can see I've been looking into user roles and it would seem that there are 100 plugins to help me control what a user can edit or publish but they don't get any more specific. We have a custom post type called Chapters and we have hundreds of users who can view said Chapters. What we want to do is add a new user role that can only view certain posts within the Chapters post type. So we have 51 Chapters and we only want the new role to see 31 of the 51 chapters. EDIT: I'm talking about the front-end. Our site requires subscription to access it so the new user role would be a like a subscriber, only they couldn't see specific "Chapters"
Using plugins like Paid Memberships PRO or s2member would be easiest solution for your purpose. You can create new user group and there capabilities. After that you can select which user group can see your post.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, users, user roles" }
Make loop alphabetical I have a simple loop but it returns it in any order. What I'm looking for is to alphabetize the loop. I've tried a few different things but Can't seem to get it to work. <?php // Start the loop. while ( have_posts() ) : the_post(); // Include the page content template. get_template_part( 'content', 'grid-projects' ); // End the loop. endwhile; ?>
this is what worked for me. works a treat. $child_pages = new WP_Query( array( 'orderby' => 'name', 'order' => 'ASC', 'cat' => '41' ) ); while ( $child_pages->have_posts() ) : $child_pages->the_post(); get_template_part( 'content', 'grid-projects' ); endwhile; wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop" }
How to order posts by meta value? All posts are using a custom field "deadline" (format: yyyy-mm-dd). How do I make my category page order posts by `meta_key` "deadline" and `DESC`? I use this: if ( get_query_var( 'paged' ) ) { $paged = get_query_var('paged'); } elseif ( get_query_var( 'page' ) ) { $paged = get_query_var( 'page' ); } else { $paged = 1; } query_posts( array( 'paged' => $paged , 'cat' => $category_id , 'meta_key' => 'deadline' , 'orderby' => 'meta_value' , 'order' => 'DESC' )); get_template_part( 'loop' ); but it doesn't work to order posts by `meta_value`.
As mentioned above, never use `query_posts`, as it breaks a lot of stuff. Use a filter like `pre_get_posts` instead. The filter `pre_get_posts` allows you to edit the query before it gets executedby WP. The following code will order by the meta value you want. I made it so it only works on the main query of a page and with the post type `post`, but you can edit it filter it further: function wpse194643_special_sort( $query ) { //is this the main query and is this post type of post if ( $query->is_main_query() && $query->is_post_type( 'post' ) ) { //Do a meta query $query->set( 'meta_query', array( array( 'key' => 'deadline' ) ) ); //sort by a meta value $query->set( 'orderby', 'meta_value' ); $query->set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'wpse194643_special_sort' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "order" }
Permalinks stopped working - NO update, mod_rewrite enabled, .htaccess not touched At first, my permalinks and all worked. My permalinks were in `/year/month/post/` format. Today I found out when I try to open an _Anspress_ question, I get a 404. (that worked too, last time I checked) Then I read somewhere I need permalink format of `/postname/` to display Anspress questions. So I changed it to `/postname/`. Now nothing except `index.php?p=xyz` is working. All links to pages throw a 404. I tried changing back to `/year/month/post/` , but that did not help. Tried going to _Permalinks_ and clicking _"Save settings"_ , but that did not help either. Tried `a2enmod rewrite` (although it has worked before), no help. I have no idea. It worked 30 minutes ago.
Fixed. Maybe an Apache update or something did this to me. I changed `AllowOverride None` to `AllowOverride All` in `/etc/apache2/apache2.conf` for the `/var/www` folder.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "permalinks, 404 error" }
Blank spaces show as a question mark I have a client who wanted to restore her old website from 5 years ago with a very small budget. I suggested that she at least uses Wordpress for CMS and now she has a limited editing capability of a portion of the text on each page. We kept all the old php files for the front end and just request the Wordpress content for the left column of the page. Now, all extra blank spaces that were in the text show up as question marks inside a black diamond. They show as proper blank spaces in Wordpress editor, and in PHPmyAdmin. Our old pages all have UTF-8 encoding. What I am confused about is that when I enter a double space in Wordpress now, the "new", just made double spaces **also** come out as question mark on the front end but display as space in MySQL. Shouldn't TinyMCE make `"&nbsp;"` for this? !enter image description here
This has solved my issue mysqli_query ($connection, "SET NAMES 'utf8'"); <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "tinymce, encoding" }
Maximum post size? I use a form to allow users to post tutorials on my website. When there are too many pictures uploaded, it seems like the site reaches a limit and stop uploading them: the post has only the first half of the uploaded photos. Does it mean there is a limit post size ? If yes, how can I increase it ?
So I couldn't upload more that 20 pictures per post, that was the issue. I had to ask my host to modify max_file_uploads Servers are usually set at 20 uploads at a time so if you want more, just ask your hosting service of modify it in php ini.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "uploads" }
Change title in head on Archive page I'm having problems with figuring out how I can change the title on my archives pages. I now have a title like this: <title>Jobs Archive - The Company</title> But I would like to have a title like this: `<title>Jobs - The Company</title>`. Without the _Archive_ . This for all my archives pages for all my custom post types. Google didn't help me much, can you help me?
You can change it via the category template (if you have multiple category templates you'll need to edit all of them; if you have archive.php, you need to edit it only there). Otherwise you can use the Yoast SEO plugin which have settings for naming the archives (actually I think that almost all SEO plugins have those settings).
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "custom post types, archives, title, custom post type archives, wp head" }
Easy reading or transfer of data from posts? Plugin usually transfer data using code like `[espro-slider id=21]` , is there a short way to read it or do they use regex to read it. If not is there a short way to define variable in post and use it directly in back-end. I am trying to read information from post and use it in page template to display custom code. please help.
`do_shortcode([espro-slider id=21])` will process the shortcode and return the result. The Codex describes exactly this example: // Use shortcode in a PHP file (outside the post editor). echo do_shortcode( '[gallery]' ); You can often just call the callback directly also: function generic_shortcode_callback($atts,$content) { return "Yay! ".$content; } echo generic_shortcode_callback('',' Me!'); VS: function generic_shortcode_callback($atts,$content) { return "Yay! ".$content; } add_shortcode('yay','generic_shortcode_callback'); $sc = do_shortcode('[yay]Me[/yay]'); echo $sc;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, posts, variables" }
How to call theme default widget in custom template? I have default widget available called "Recent Post" created by theme. I want to call that widget in my custom template which I made. I am trying in following way , But that is not working. <?php get_widget( 'WP_Widget_Recent Posts' ); ?> !enter image description here
Try this <?php the_widget( 'WP_Widget_Recent_Posts', array('number' => 10, 'title' => 'My Title Goes Here'), $args ); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "widgets" }
meta_value timestamp older than now In my `wp_posts` table I want to select the rows `where post_type == event`. I also want to a connection with `wp_postmeta` from the specific row. In my `wp_postmeta` table I want to do a where like this: `Where post_id == (post id from wp_posts) and the meta_value from meta_key == event_date_end_timestamp is older than now`. So in my wp_postmeta I have : !enter image description here But how can I form my query to do this?
<?php $args = array( 'posts_per_page' => -1, 'post_type' => 'event', 'meta_query' => array( array( 'key' => 'event_date_end_timestamp', 'value' => time(), 'type' => 'numeric', 'compare' => '<' ) ) ); $programs = new WP_Query($args); ?> <?php while($programs->have_posts()): $programs->the_post(); ?> <h1><?php the_title(); ?></h1> <?php endwhile; ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, wp query, query, wpdb" }
Which Hook? Hide attachments from specific post types in media library as the title implies - I would like to suppress attachments of a specific post type(s) from showing up in the "Media Library" Not asking for a code example, but if someone can point me to the right hook it would be much appreciated. Thanks!
For the media library you can use the `pre_get_posts` hook targeting `upload.php` by means of `$pagenow`, a `global` variable, or even better, because globals are the devils child, by means of `get_current_screen()`. I'm assuming you want to target the media modal tab too - because targeting only one, but not the other, doesn't make much sense after all -, you can do that via the `ajax_query_attachments_args` hook.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "hooks, media library" }
Use dashicons in menu items? I tried to add _dashicons_ to my menu items but once I save the menu, the whole item doesn't appear on my site. I tried with: <span class="dashicons dashicons-arrow-down"></span> Is there a way to do this ?
the dashicon will only available to you on admin menu images. if you want it on your menu item then you must followed option B. means using awesome font library. for this you need to add it from this : ` i hope this will helps.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "menus" }
Override static home page post In functions.php is it possible to dynamically set the static home page? The condition could be anything, but for example by domain: if ( $_SERVER['HTTP_HOST'] == 'domain-one.com' ) set_front_page_slug('domain-one-home'); else if ( $_SERVER['HTTP_HOST'] == 'domain-two.com' ) set_front_page_slug('domain-two-home'); Note that it should not permanently change the home page set in the WordPress Settings, only for the current page load. I want different visitors to see different homepages. Any approach welcome that can neatly override the default home page.
This is the best solution I've been able to come up with, and satisfies the need to dynamically set the home page (not template) based on factors such as subdomain. add_action( 'pre_get_posts', 'dynamic_home' ); function dynamic_home( $query ) { if ( is_front_page() && $query->is_main_query() ) { $query->set( 'post_type' , 'my-cpt' ); $query->set( 'name' , 'a-slug' ); $query->set( 'p' , null ); $query->set( 'page_id' , null ); } } In the above some_custom_condition() could contain logic such as if the current URL is the home page. This example overrides the home page with a custom post type, but could be simpler if just page content types were used. Setting the template alone is not sufficient and does not scale to potentially unlimited number of home pages. Such a scenario would be each user of a site having their own personalised home page on their own subdomain.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "homepage, frontpage" }
Change wp-content without changing the name of the folder This does not work # BEGIN WordPress <IfModule mod_rewrite.c> RewriteRule ^/index\.php$ - [L] RewriteRule ^/css/(.*) /wp-content/themes/themename/css/$1 [QSA,L] RewriteRule ^/js/(.*) /wp-content/themes/themename/js/$1 [QSA,L] RewriteRule ^/img/(.*) /wp-content/themes/themename/img/$1 [QSA,L] RewriteRule ^/font/(.*) /wp-content/themes/themename/font/$1 [QSA,L] RewriteRule ^/plugins/(.*) /wp-content/plugins/$1 [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
Strip the preceeding forward slashes from your rules: Example (incorrect) RewriteRule ^/css/(.*) /wp-content/themes/themename/css/$1 [QSA,L] Example (correct) RewriteRule ^css/(.*) wp-content/themes/themename/css/$1 [QSA,L] All rules (correct) # BEGIN WordPress <IfModule mod_rewrite.c> RewriteRule ^/index\.php$ - [L] RewriteRule ^css/(.*) wp-content/themes/themename/css/$1 [QSA,L] RewriteRule ^js/(.*) wp-content/themes/themename/js/$1 [QSA,L] RewriteRule ^img/(.*) wp-content/themes/themename/img/$1 [QSA,L] RewriteRule ^font/(.*) wp-content/themes/themename/font/$1 [QSA,L] RewriteRule ^plugins/(.*) wp-content/plugins/$1 [QSA,L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "htaccess, directory" }
the_permalink displays post ID URL for future posts I use a WP template to generate an email newsletter. I display future posts and until recently using the_permalink displayed the full human-readable URL (e.g. /this-is-a-page). Now it displays the post ID URL (e.g. ?p=5800). How do I get WP to display the human-readable URL? More strange, perhaps, on the Add/Edit page for my future entries, when I add or update a story to be published in the future, the message up top "Post updated. View post" link goes to the post ID URL. However, the View Post button to the right of the Permalink, located directly under the entry title input field, goes to the human-readable URL. It's a major PITA and totally counter-productive to manually convert the post URLs to human readable URLs. I need the HTML output from my template to set up HTML emails before the stories are published. Any ideas how to retrieve and display human-readable URLs for future stories? Thanks for any help and insights.
Permalink settings are available under `Permalinks` under the `settings` menu. I have faced a similar issue resetting the options here to non rewritten URLs and then back to the rewritten URLs should reset any issues with `.htaccess` file
stackexchange-wordpress
{ "answer_score": 2, "question_score": 5, "tags": "permalinks" }
Custom URL segment parameters for posts I need to add a custom parameter/segment to the post URL. For example, when I have a post at `example.com/post-name`, I need to add another segment like `example.com/post-name/places`. After that, I need to add a dynamic segment like `example.com/post-name/places/dynamic-value`. I can't use `?key=value` parameters, it needs to be segmented. I've tried to work with `add_rewrite_rule()`, but it doesn't seem to work. How can I achieve something like that?
Have you thought of making post type, taxonomy, terms? If you do so, it will be a lot easier for you to code and get the above urls. If any confusion, let me know.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting, parameter" }
Reliable method to detect mobiles I'm running a WordPress site and wanna setup a mobile site based on it. I've tried some plugins like Mobile Themes which allows me to implement a different theme for mobile. The problem is when I use memcached, the main theme and mobile theme is confusing very often(e.g. access the site by mobile but meet a main theme) I'm considering another way to do this now. Use a PHP mobile detective script, and write the code in all theme template files(e.g. `header.php`) like: if(is_mobile()) { // mobile theme code } else { // main theme code } for this, I need only to maintain one theme. I've never tried this way, not sure if there is any problem, and I didn't think about how to handle the style.css yet.(There are some plugins allow me to use different style rules for mobile, but I've never tried) Does anybody could provide some suggestions?
In my experience `browscap.ini` based checks are not terrible - at least. There is - probably not the only one - an PHP implementation with browsecap-php that can be used for PHP projects and would be suitable for WP projects too. As for a WordPress implementation, there is the plug-in - I know of - PHP Browser Detection, which as far as I can tell does a good job implementing the functionality. Last but not least, I can't give you any numbers on reliability though, so lets just say, seeing the discussion under your question, you have been warned.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, mobile" }
wp-config.php being deleted I am helping someone sort out a site, it suddenly wanted to be installed instead of showing the site itself. I found that the wp-config.php file was missing. Fortunately there was a backup and I restored the wp-config, about a week later it was deleted again. This time I extracted the backup zip file to a directory so it would be easily available, copied the wp-config and got the site working. Today the wp-config has disappeared again. But a 'smoking gun' is that the wp-config file in the backup directory has also gone. (yes, I still have the zip). I suspect there is a plugin on the rampage targetting that file name. I have suggested a fresh install and reinstall all the plugins, it might come to that. But before doing that, short of disabling them all, any suggestions on how to work out which one plugin it might be? Or what might be doing this?
The problem turned out to be that wp-config was infected with some sort of code. Typical of what you see at the top of infected .php files. I have cxs running on the server and it was, quite rightly, detecting the malicious (I assume) code and quarantining the file. When I restored the file, because I didn't look at the content, I was restoring an infected file each time and cxs was doing its job. It was pretty frustrating trying to work it out, something twigged for me last night. Hope this helps someone else.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "wp config" }
Taxonomy terms sort by... Last name! I have a custom Taxonomy named 'authors' where I insert additional authors. My question is: is it possible to list all the taxonomy terms order by "Last Name". If I order by name clearly it looks like: * Andrea Red * Daniel Green * Elena Blue Instead of this I would like to sort by Last Name: * Elena Blue * Daniel Green * Andrea Red Do you have any advice to do it? Is it better to add a New Custom Field in Custom Taoxnomy where I specify the Last Name and then I sort by that term? Thank you very much Elena
You can try the MySQL function `SUBSTRING_INDEX()` within the `get_terms_orderby` filter: /** * Order by the last word in the term name * @link */ add_filter( 'get_terms_orderby', function( $orderby, $args ) { if( isset( $args['orderby'] ) && 'wpse_last_word' === $args['orderby'] ) $orderby = " SUBSTRING_INDEX( t.name, ' ', -1 ) "; return $orderby; }, 10, 2 ); to order by the _last word_ in the _term name_. Here we activate the _last-word_ ordering through our custom `wpse_last_word` argument: $terms = get_terms( 'category', [ 'orderby' => 'wpse_last_word' ] ); You can also add the `wpse_last_word` argument, through the `get_terms_args` filter, if you need to override some term query. I recently used this method here for posts.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "taxonomy" }
How to set an option for all sites in my Multisite network? I have a multisite instance of WordPress with almost 100 sites. I need to set an option for a network-wide installed plugin but I don't want to go to each site dashboard to set this option by hand. How could I do ? The option I want to change is a classic option, not a network-wide one. It comes from a plugin that I did not write. Want I need it to change the value of that classic option for all sites in my network at once.
Excuse me if I'm misunderstanding you, but aren't the functions `add_site_option()`, `update_site_option()` and `get_site_option()` pretty much, they fall back to single site functions, if not used in a multisite environment, only there for the purpose of having network-wide options. * * * Update: Regarding your need to change a single site option for all sites in your network. Get all sites of the network with `wp_get_sites()`, which returns an array of arrays. You can use the array to loop through your single sites in your multisite installation. Make use of `switch_to_blog()` and `restore_current_blog()` while looping against the `$blog_ids`. In between the loop after switching and before restoring, use the single site options functions `add_option()`, `update_option()` and `get_option()` as needed.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 6, "tags": "multisite, options" }
WordPress keeps autoplaying my Youtube-Links no matter what I write WordPress (with the LayerSlider plugin) keeps autoplaying my video no matter what code I use. Here's the embed-Link for the video: `<iframe width="840" height="473" src=" frameborder="0" allowfullscreen></iframe>` And here's how I changed it: <iframe width="840" height="473" src=" frameborder="0" allowfullscreen></iframe> I tried both "?autoplay=0" and "autoplay="0" after the link. Is there any specific way I have to embed the video for it not to play automatically?
Did you know you can just copy paste a youtube URL onto its own line and it transforms into a video player auto-magically via **oembed**? There's no need for embed codes/shortcodes/plugins Simply create a blank line, and take the address of the youtube video and paste it into the editor: !oembed gif courtesy of clickwp These youtube videos should not play automatically WordPress will pick up any URL for Youtube on a line by itself and convert it into a Video player automatically via OEmbed, the same is true of other services such as soundcloud, instagram, vimeo, flickr, tweets etc etc
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "api, embed, youtube, video player" }
Add Image With Changeable Link in Custom Field In my WordPress site, I want A image with changeable link in bottom of every post. The Image will be fixed but links should be changeable. I want This changeable link option in the post editor of wordpress so that I an Change the link as different post-different link. This links are the same post but in different language from sub-domain website. Please help. Sorry for bad English. Thank You.
I made this code with help from Google search. And it works fine. I added this code in single.php bottom of the post. Now, I simply add link in every post but image are same. Thanks. :) <?php if( get_post_meta($post->ID, "imglink", true) ): ?> <p><a href="<?php echo get_post_meta($post->ID, "imglink", true); ?>"><img src=" <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field" }
Permalinks - .htaccess According to the official WordPress docs, when you save your Permalinks it updates your .htaccess file (< However, when I make Permalink changes and save them I don't see any .htaccess updates. Can someone clarify if the WordPress docs are inaccurate or if there's something I'm missing.
> According to the official WordPress docs, when you save your Permalinks it updates your .htaccess file ... This isn't correct. When you switch from default-- `?=` permalinks which are nothing but pure PHP URL parameter passing-- to anything else then WordPress will create a `.htaccess` file if it can, or tell you to create one. Once that file is created the permalinks are generated entirely internally to WordPress. The `.htaccess` file does not need to be, and isn't, updated every time you change permalinks. You can see the `file_exists()` check in the `save_mod_rewrite_rules()` function. Specifically, what happens in that WordPress creates a `.htaccess` file telling the Apache to send all requests to the `index` page thus allowing WordPress to take over.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, htaccess" }
Where and when does WordPress invoke routes One of my URLs for which I'm wanting to create a Category Archive is coming up with a 404 despite having matching routes and, supposedly, matching templates. I'm going through the core WordPress code (groan) and haven't figured out where routes are invoked. It seems that the Categories are decided in `query.php` in the `parse_query` function however I can't see where routes are being used to map URLs to files.
`parse_query` is where the majority of the work is done. Query vars and `is_` conditionals are set, and `template-loader.php` just checks those `is_` conditional tags to load the appropriate template.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "categories, query, routing" }
Rewrite rules ignored Why are my rewrite rules being ignored by WordPress? I've got the following rule added: news/([0-9]{4})/?$ archive-news.php?year=$matches[1] but the URL `news/2015` gives a 404. Why?
All rewrite rules should point to `index.php`. This is a reference to the main `index.php` file through which all requests are routed, not a template file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rewrite rules" }
WP::is_main_query() Not Working I am Trying to add some content before the posts container I use this code add_action( 'wp', 'mainFunc' ); function mainFunc( $query ) { if ( is_home() && $query->is_main_query()) { add_action("loop_start","anotherFunc"); } } and I have anotherFunc() too. but I get > Fatal error: Call to undefined method WP::is_main_query() in C:\xampp\htdocs\wp\wp-content\plugins\topMessage\topmessage.php on line 40 Any Ideas ?
Wrong hook, because what gets passed to `wp` is the > Current WordPress environment instance not > The WP_Query instance like it is e.g. passed to `loop_start`. You could actually just do your check inside the function callback you hook to `loop_start`. Edit/note: You could just have done `global $wp_query;` inside the `wp` hook, it is actually the first one where access to `$wp_query` is possible, to have access to it - not that I recommend doing it though. A better place - or at least the one I probably would go for - to hook into is the `pre_get_posts` action, which does get passed `$query` \- the `WP_Query` object - by reference.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, posts" }
Storing post_meta fields in array I need to have 8 separate post meta fields on each post in wp-admin (shown in a custom meta field box). I'd like the data from these 8 fields to be stored in an array as one post_meta field for easy parsing on the front-end. What's the best way to do this? I have found examples of how to do this via PHP, but not how to combine inputs in the backend on save.
I agree with kraftner's comments to the question. This is a bad idea and you stand a good chance of regretting it later. Store you data as granular post meta values. Everything is easier later on. However, `add_post_meta()` and `save_post_meta()` will serialize objects/arrays for you. You don't have to do anything special: update_post_meta(1,'my_bad_idea',array('i','will','regret','this','later')); And `get_post_meta()` will unserialize it for you: var_dump(get_post_meta(1,'my_bad_idea'));
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post meta" }
Using Customizer value in an external PHP file inside a theme I'm working on a theme for a company and they don't want the users to touch the code at all. So as I love, they asked me to use Customizer API. Now, there's a PHP file in the theme which we don't call anyone but on a MailChimp form, via AJAX. So basically, this PHP file is inside /inc/helper/mailchimp.php file but only gets called by an AJAX script. So is there any way to render Customizer value inside the form? And the value will MailChimp API key so we don't want this to appear anywhere in the source code. Anyone knows a way to do this? I have completed the entire theme and I just need to finish this. :)
Coming back to this thread after five years as it's still wasn't marked as answered. Milo in the comments pointed out the answer: Trying to avoid including wp-load.php
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, themes, ajax, theme options, theme customizer" }
WordPress admin menu formatting issue I'm having an issue with my admin menu in WordPress. As you can see in the image below the formatting of the menu is out of order. This happens whenever I first land on one of the admin pages but if I refresh the page the menu looks fine. I tried disabling my plugins but none of them seem to be causing the issue. ![WordPress admin menu](
Otto has suggested a fix in Chrome itself until the bug is resolved: * Go to chrome://flags/#disable-slimming-paint * Enable the "Disable slimming paint" option. * Ensure that the "Enable slimming paint" option below it is not turned on. * Relaunch Chrome. If you don't want to take this approach you can fix this with CSS: function chromefix_inline_css() { wp_add_inline_style( 'wp-admin', '#adminmenu { transform: translateZ(0); }' ); } add_action('admin_enqueue_scripts', 'chromefix_inline_css'); If you just want a plugin to do it: <
stackexchange-wordpress
{ "answer_score": 27, "question_score": 25, "tags": "admin menu" }
How are roles stored in the database? I know roles are defined < but how are they stored in the database? For instance, how is "Super Admin" stored i.e. 'super_admin'?
The core functions: * `is_super_admin()`, * `grant_super_admin()`, * `revoke_super_admin()` fetch the super admins data from the `wp_sitemeta` table with: $super_admins = get_site_option( 'site_admins', array( 'admin' ) ); It's stored as a serialized array of user logins, for each site, like: a:1:{i:0;s:6:"louiev";} It's possible to override it with the global `$site_admins` array. On the other hand, the general user roles ( _admin_ , _editor_ , _author_ , ...) are stored as serialized arrays, for each user, like: a:1:{s:13:"administrator";b:1;} in the `wp_usermeta` table under the `wp_capabilities` meta key and/or the `wp_{$blog_id}_capabilities` meta keys. Note that the `wp_` prefix might be different on your install.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "user roles" }
Bootstrap Drop Down menu is not working Bootstrap dropdown is working when i added the jquery( < ) in footer and by deregistering wodpress default jquery. When i disabling the default jquery my plugins are not working. Can any one help me on this please?
My problem got solved by commenting the some codes in function.js(theme js folder) that generating "Expand child menu" text.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, functions, jquery, twitter bootstrap" }
What is the correct way to include my new functions and scripts in WordPress? To include new functions we can write them in the theme's functions.php. But I have to write my own functions in a new file rather altering the theme's function.php. I can write any custom js action in footer.php, but I need to write it in other file. How can I do this? Is there any correct way to do this?
You can simply use `require`, `require_once`, `include` or `include_once` functions to include custom PHP files in your theme. require( 'folder/custom.php' ); Usually you should keep your custom PHP files in a folder. Developers vote against using `require_once` because it is a little slower than `require` since it requires the system to keep a log of what's already been included/required.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, theme development" }
Does the WordPress API have Modal Dialogs Does the WordPress API have a Modal Dialog like BootStrap does? In my WordPress Plugin admin page - the plugin settings page accessed through the Dashboard - I would like to have modal dialogs appear and allow the user to edit settings. WordPress has the classes `button`, `wp-list-table`, `tablenav`, etc. I was thinking that there might also be a modal dialog class with some associated Javascript API functions to make it appear and disappear?
Yes, WordPress has modal dialog and it is called as Thickbox, but I am not sure how flexible it is to implement what you want to. Here is the code - <?php add_thickbox(); ?> <div id="my-content-id" style="display:none;"> <p> This is my hidden content! It will appear in ThickBox when the link is clicked. </p> </div> <a href="#TB_inline?width=600&height=550&inlineId=my-content-id" class="thickbox">View my inline content!</a> Refer for more details - <
stackexchange-wordpress
{ "answer_score": 9, "question_score": 2, "tags": "plugins, api" }
Get child categories of custom taxonomy category? I am using custom `post type : portfolio` and have taxonomy for that `portfolio_category`. I need to get sub categories for a particular category using the above custom taxonomy. In short, How can I get the child categories for `taxonomy=portfolio_category&tag_ID=80&post_type=portfolio`?
Use `get_terms()` to get the child terms of a given term. You need to feed the specific term id to either > * **`parent`** > > > (integer) Get direct children of this term (only terms whose explicit parent is this value). If 0 is passed, only top-level terms are returned. Default is an empty string. **OR** > * **`child_of`** > > > \- (integer) Get all descendents of this term. Default is 0. Note: the difference between child_of and parent is that where parentonly gets direct children of the parent term (ie: 1 level down), child_of gets all descendants (as many levels as are available) ## EXAMPLE: Get all descendants of term ID 80 ( _Requires PHP 5.4+_ ) $terms = get_terms( 'portfolio_category', ['child_of' => 80] ); For only first level children, change `child_of` to `parent`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy, categories" }
Chrome Version 44.0.2403.89 m is trying to force HTTPS With the release of Chrome Version 44.0.2403.89 m, I've noticed that our site is now completely broken. All of the HTTP URLs are being redirected to HTTPS URLs, which is a problem because our site does **not** support HTTPS. Please note, this is not happening in any other browser, and was working on the previous Chrome release. I've tried to replace all of our stylesheet calls with relative links, and that has worked, but the images that are loaded in automatically or through absolute paths as well as the navigation is still broken. Please see below image for the error page that is thrown when navigating, after accepting the security warning and proceeding. ![Error thrown when navigating to a page.]( Anyone have any advice as far as updating perhaps the .htaccess file goes, or something in functions? Thanks.
**Solution 1:** Enable mod_header on the server and added this rule to my appache2.conf file: <IfModule mod_headers.c> RequestHeader unset HTTPS </IfModule> **Solution 2:** Or you need to add the code to fonction.php file of your current theme: function https_chrome44fix() { $_SERVER['HTTPS'] = false; } add_action('init', 'https_chrome44fix',0);
stackexchange-wordpress
{ "answer_score": 6, "question_score": 7, "tags": "https, http, google chrome" }
Structure of postmeta meta_value for woocommerce product download So I'm working on a monster script to port all of our existing stuff from Joomla/Virtuemart to Wordpress/WooCommerce. So far I've got just about everything done with moving over our product categories and products, I just need to figure out the structure of the `_downloadable_files` postmeta. Using this as an example: a:1:{s:32:"ded830cf64e3c42c4f7ac5aecd7c5c86";a:2:{s:4:"name";s:0:"";s:4:"file";s:114:" How is the `s:114` just before the file url generated? That is the only part that changes that I don't know how to generate. Any suggestions would be greatly appreciated!
In short, this is serialized data and this is how data is stored from a custom field (and many other datastrings) in the db. `s:114` is auto generated and simply means that the value ` is a string and is 114 characters long. This is used when the data is read and used. If the URL value changes, the string length will change as the length of the string changes You will need to go and have a look at data serializing and unserializing
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "database, post meta, woocommerce offtopic" }
Get custom field values of taxonomy terms I added a Custom Field named 'cognome_nome' in my Custom Taxonomy named 'authors'. I would like to display in a Archive Page a list of all 'cognome_nome' values of the terms. Examples: 1.term * Name: Elena P * slug: elena_p * cognome_nome: P Elena 2.term * Name: Andrea P * slug: andrea_p * cognome_nome: P Andrea I would like to display: * P Elena * P Andrea and so on... Do you think it's possible? Thank you in advance :) EDIT I'm using this code to list all the terms: $terms = get_terms( 'authors' ); if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){ echo '<ul>'; foreach ( $terms as $term ) { echo '<li> <a href="' . get_term_link( $term ) . '">' . $term->name . '</a></li>'; } echo '</ul>'; }
Are you using Advanced Custom Fields plugin? If you are, try this if it works: foreach ($terms as $term) { // $cognome_nome will be "P Elena" or "P Andrea" in your case $cognome_nome = get_field('cognome_nome', $term->taxonomy.'_'.$term->term_id); }
stackexchange-wordpress
{ "answer_score": 7, "question_score": 2, "tags": "custom taxonomy" }
Manually Create PHP Page For A Redirect I am new to wordpress and working on something for a friend, I have FTP access, and am trying to upload a php file, that checks the platform and redirects the user either to the iTunes store if they are on an iOS device or force downloads a file if the user is on any other platform. I have the PHP file written, but it looks like wordpress pulls all it's information from a database and inserts it into templated pages. I need for users to just be able to access this page unless someone knows of a better method of doing this in wordpress. I need some help, can anyone point me in the right direction?
I guess you are talking about a specific page, for example domain.com/page? So you can create a generic page template (and select it for the page in WordPress admin panel) or create a template for the specific page. See instructions here. In this template you can add your php code for the redirect. If this redirection would be done for the whole site, not just one page, you can always edit the generic page template or the header.php file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, redirect, wp redirect" }
WooCommerce - Create Products Programatically I'm writing a plugin that will automatically import products via JSON API. I need to programatically create/update products. I did a research and it seems everyone is using `wp_insert_post()` and `update_post_meta()` for this, ie this and this However, I found that there's the `class-wc-api-products`, where are various functions for adding/editing products and variations. Is there any reason why people don't use something like: $wc = new WC_API_Products(); $wc->create_product( $data ); It seems to me more future-proof to use native WC classes for this, am I wrong?
Technically speaking, Woocommerce products are just another WordPress post object with a customized post type (which is `product` in this case). If you take a look at the `create_product` function inside `class-wc-api-products.php`, you'll see this line: // Attempts to create the new product $id = wp_insert_post( $new_product, true ); So the API ends up using `wp_insert_post` eventually. I guess you can do both but it's obviously using what WooCommerce API provides to create a WooCommerce product is a better way to go.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "posts, plugin development, woocommerce offtopic" }
Why can't I save permalink "360" for a page? I am trying to save my page with permalink "360" but for some reason WP keeps updating the permalink to "360-2". I have checked everywhere in my WP and there is no page or post that uses permalink "360". Is 360 a permalink for something internal? If not, what is the problem?
The problem comes with using only numbers as URLs. Here is a forum thread in WP that discuss this issue. I'll cite Otto: > WordPress 2.3 and up does not allow the post or page slugs to be all numeric. This is because that URL scheme will conflict with multi-page posts. > > There is no fix. Change them to something else. > > Alternatively, a plugin exists to allow this, if you give up on multi-page posting: < > > More info here: <
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "permalinks" }
Empty tax_query array returns an empty array I would like to return all posts when the tax_query['terms'] is empty. $args = array( 'post_type' => 'product', 'posts_per_page' => 15, 'paged' => $paged, 'post__not_in' => $exclude, 's' => $filter, 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => array(), ), ), ); Unfortunately I didn't find solution for the problem. As you can see the array is empty: `'terms' => array(),`but I would like to return all posts. How can I achive that?
As already hinted by @Milo, check if you have terms before appending your `tax_query` You can try the following: ( _Requires PHP 5.4+ due to short array syntax, revert to old syntax if necessary_ ) $args = [ 'post_type' => 'product', 'posts_per_page' => 15, 'paged' => $paged, 'post__not_in' => $exclude, 's' => $filter, ]; // Append our tax-query if we have terms. Make sure it is a valid string or array $term = 'DEFINE YOUR TERM HERE'; if ( $terms ) { $args['tax_query'] = [ [ 'taxonomy' => 'product_cat' 'terms' => $terms, ] ]; } $q = new WP_Query( $args );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "wp query, query, terms, tax query" }
403 Forbidden Error on subdomain I've got a bit a troublesome issue. In my development site installed at a subdomain < I'm getting 403 errors on all pages except my homepage. Clicking on 'Discounts' in the main menu or 'Contact' in the footer menu you'll see these occur (other links are # at present). I've gone through things with GoDaddy and it does not seem to be issues with .htaccess. I've de-activated all plugins and changed to twentyfifteen theme and I still have the same error. Originally it occurred when I tried to modify the permalink structure. To access the dev site! you'll need these credentials. User: havefun pw: inthesandbox The one things which I'm suspicious about is that the 403 error reads `You don't have permission to access /BroadwaySelect/staging/contact/ on this server.` while the url is < This would seem to suggest to me perhaps something is up with the subdomain forwarding? Any help or tips would be awesome. Thanks a ton!
So this issue had to do with File permissions. I believed that I had already checked into this to make sure that permissions were set properly, but I must have erred. I went to the subdomain folder 'staging' which contains my WP install and turned on User 'read' and 'write' permissions, which were inactive. So now Web User and Owner permissions have been all set with read, write and execute permission. Hope that helps someone!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, subdomains" }
Cannot retrieve Custom Taxonomies (Disappeared) I was deleting custom posts from backend (wordpress dashboard). I have made a front-end form for a custom post type, it has check boxes for custom taxonomies. Now the taxonomies are not being fetched in the front-end. :( Please help. I don't know if this is a word press cache issue or something else. Has anyone seen anything like this before? **The Custom taxonomies in front-end which are no longer fetch-able** ![The Custom taxonomies in front-end which are no longer fetch-able]( **But are visible in the back-end** ![But are visible in the back-end](
The solution to this was pretty simple.Had I read WP documentation thoroughly for `get_categories` Apparently I had to set this `'hide_empty' => false` when I fetched my taxonomies :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, custom taxonomy" }
Conditional statement checking two conditions for CPT and Custom Taxonomy I am trying to write a conditional statement which checks if the single custom post type also has a custom taxonomy term associated with it. My code is: if (is_singular('my_cpt')) && (has_term('myterm', 'mytaxonomy', $post->ID )) { But somehow, I am getting unexpected '&&' (T_BOOLEAN_AND) error. Please help.
Yes because your code has syntax error. It should be this. if ( is_singular('my_cpt') && ( has_term( 'myterm', 'mytaxonomy', $post->ID ) ) ) { } Did you notice `if` condition should close just after `is_singular('my_cpt')`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "custom post types, conditional tags" }
How can i make WP_Query return post image and categories? I have a sidebar widget that will display related posts based on a custom meta field. The query works, but its very wasteful. All i need is the post title, featured image and the categories of the post. Currently the following query is returning all of the content for the post along with a massive amount of data that i dont need. I dont want to be killing my server by pulling huge amounts of data from the database that i dont need $myquery = new WP_Query( "post_type=post&meta_key=nb_gameids_key&meta_value=14&order=ASC" ); To best explain the data i want ill use an sql query that would give me the data i want. I know the database isnt structured this way its just for an example. SELECT title,image,category FROM posts WHERE nb_gameids_key = 14 ORDER BY datecreated LIMIT 6
You don't need to worry to much about your query as there is not much you can do about it. You can unfortunately not just only query categies, post titles and images natively using `WP_Query`. Post categories needs to be called separately inside the loop, just like featured images. If you dig deeper into core, you will see that all postdata and post terms are cached, so when you think you are making extra db calls, you are not. The cache is first checked for the requires data, if it is, the data is retrieved from the cache, otherwise the db is queried and the data is cached for later queries. You can add `'no_found_rows' => true,` to your arguments if you are not going to paginate your query. This makes the query faster as it ignores pagination. Alternatively, you can use `get_posts` which has this already build in Also, you can make use of transients to store the result from a query and only flush the transient when a new post is added in a particular category or custom field
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "wp query, custom field, widgets" }
Responsive Wordpress Gallery I have been trying to make my Wordpress Gallery responsive with the help from another post: Making WordPress Gallery (.gallery-item) Responsive? I would also like the original 5-column gallery to display three columns on a tablet. I have used the following css: /* For displaying 3 columns on tablet */ @media only screen and (max-width: 800px) { .gallery-columns-5 .gallery-item { width: 33% !important; } } This works and is now displaying three columns. But it leaves a blank space after every 5th picture. As suggested in the other post i tried .gallery-columns-5 .gallery-item:nth-child(5n+1) { clear: none; } But this does not seem to work. Does anyone know how to get rid of the blank spaces and still display the page correctly on both tablets and desktops? The URL for the page is: <
You need add some CSS to make it auto clear left after each 3th item and need to hide `<br>` tag Update your code like this- /* For displaying 3 columns on tablet */ @media only screen and (max-width: 800px) { .gallery-columns-5 .gallery-item { width: 33% !important; } .gallery-columns-5 br { display: none; } .gallery-columns-5 .gallery-item:nth-of-type(3n+1) { clear: left; } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "gallery, responsive" }
Target h1 on single post page I have CSS in my theme making all H1 white. One post has a white background image so I want to target this post specifically and make the text grey. h1.entry-title targets all pages correctly. I have tried a few iterations of the below but can't get the one post to be targeted. #postid-156.h1.entry-title { color: #666666 !important; } I'm new at CSS, so hopefully I'm close.
Did you try .post-156 h1{ color: #666666 !important; } If one of your wrapper elements, like `<article>` is unsing `post_class()` the post ID becomes a class of this wrapper like `.post-156`. So you can say all h1 which are contained in a wrapper with the class `.post-156` Another possibility, if your `<body>`-Tag is using `body_class()`: .postid-156 h1{ color: #666666 !important; } Hope, this helps. Ref.: < <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "css" }
How to protect own PHP code from Wordpress updates I have written several own shortcode scripts which I place in the shortcodes.php file. My Wordpress installation is set to update to new Wordpress versions automatically, which is a good thing. But the Wordpress updates keep overwriting the shortcodes.php file, so I have to manually add my shortcode PHP code every time after an update (and I might be away a few days or so). Which is the preferred place to put my PHP code for the shortcodes that does not get overwritten? Thankfully nokul
**NEVER EVER** alter any template or file in a theme or plugin that you did not author, and this goes for any core file as well. There is no way to protect the code that you alter or add in any of those files, except maybe changing file permissions, but then again, you will run into other issues **ALL** customizations should and must be made in either a child theme or a custom plugin. Code like shortcodes as in your question must **always** go into a custom made plugin as shortcodes add functionality to your site and not your theme. You should definitely go and read the following post * Where to put my code: plugin or functions.php? This is one of the most important things that you need to consider when customizing anything for a site
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, shortcode" }
Custom Post Type Title Placeholder Is it possible to use custom placeholder for custom post title? I couldn't see any placeholder mentioned in the `labels` array argument of `register_post_type` function documentation. ![enter image description here](
Yes sure you can achive that simply using `enter_title_here` filter hook. add_filter('enter_title_here', 'my_title_place_holder' , 20 , 2 ); function my_title_place_holder($title , $post){ if( $post->post_type == 'portfolio' ){ $my_title = "Add new Portfolio"; return $my_title; } return $title; }
stackexchange-wordpress
{ "answer_score": 11, "question_score": 2, "tags": "title" }