INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
WP rest api v2 posts filter by 'search' & 'category_name' not working I am calling the api as ` I am not able to get particular posts from that specific category. I got all results from all categories.Any suggestions please.
The filter parameter was removed as part of WP 4.7, to get the results you expect you'll need to change to Make sure to change `categories=0` to whatever `uncategorised`'s `tag_ID` is. If you'd like to restore the Filter parameter, I would recommend this plugin: <
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugin development, rest api" }
Same WooComerce shop for different WP sites? I have a WooComerce Shop in one of my WP sites. Is there any way to make my other WP sites have this same shop, keeping their own themes? I have no multisite. If I add one product to the shop of my main site, the rest should be updated. I use _WC Ajax Product Filter_ plugin also. Update: I have already tried _Multisite_. But seems like it uses subdomains. In my case I have 3 differents wordpress sites that need the same shop.
Multi site will not solve your problem. Cause **_WooCommerce_** takes each site of multi site as a individual site. As far I understood you problem could be solved by using API's and which need a heavy modification. Each site of user will communicate between them through API's. When any of the product will be added or deleted or modified it will send a request to all other sites through API and they will update themselves. But as I said earlier it needs heavy modification.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "woocommerce offtopic" }
How to interfere to default search to make it search in custom fields? I'm trying to interfere default WP search (`?s=`) to make it search through posts custom fields. Firstly I'm trying to debug my search with this piece of code in `functions.php`: function add_search_in_custom_fields( $query ) { $query->set( 'post_type', 'my_post_type', 'meta_query', array( array( 'key' => 'my_key_title', 'value' => 'my_value_title', 'compare' => 'LIKE' ) ) ); return $query; } add_action( 'pre_get_posts', 'add_search_in_custom_fields' ); What's strange - that I'm getting all posts (with `my_post_type`) - doesn't matter if there is `value` or not in posts custom field. Seems like `$query` doesn't look at `meta_query` parameters at all. Any ideas?
You are getting all post because you didn't pass meta query correctly. Try this below code function add_search_in_custom_fields( $query ) { // check the query type. if ( $query->is_search ) { $meta_array = array( array( 'key' => 'my_key_title', 'value' => $query->query_vars['s'] , 'compare' => 'LIKE', ), ); // set meta query. $query->set('meta_query', $meta_array); }; } add_filter( 'pre_get_posts', 'add_search_in_custom_fields'); Hope this help !
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "query, search" }
wp_redirect () doesn't work in nginx? I made a simple redirection plugin that works like this: add_action('wp_head', 'myredir'); function myredir(){ if ( is_404() ) { $Path=$_SERVER['REQUEST_URI']; wp_redirect( ' ); exit(); } } The goal is redirect 404 errors to the old domain (I need to do a manual migration from an old website and it's going to take ages) On Apache it works fine, on Nginx it doesn't work. What can I do to fix my plugin? The Redirection plugin works fine and it looks like is using wp_redirect, so there something wrong with my code
It should not have worked on apache as well. `wp_head` is too late to make a redirect as there is already some output sent at that point and php will not send the http headers required for the redirection. You need to hook on `wp_loaded` or any other hook before output actually happens.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "redirect, wp redirect" }
How to disable site title and description when custom header is uploaded on the customizer? I'm builting my own wordpress theme and I'm trying to create a function with an if else statement to diseble the title and description of the blog when i have a custom header. if I have a custom header i have to echo <div class="table-cell"> <?php get_custom_header() ?> </div> but if not echo this code <div class="table-cell"> <h1 class="blog-title"><?php bloginfo('name'); ?></h1> <h5 class="blog-tagline"><?php bloginfo('description'); ?></h5> <div class="image-title"><img src="<?php bloginfo('template_url'); ?>/images/image.png" /></div> </div> The proplem is that is php code within the html, i not sure if you can echo this... If there's anyway of creating an If statement to hide the title and tagline only if the custom header is being used...
<div class="table-cell"> <?php if ( has_custom_header() ) : ?> <?php the_custom_header_markup() ?> <?php else : ?> <h1 class="blog-title"><?php bloginfo('name'); ?></h1> <h5 class="blog-tagline"><?php bloginfo('description'); ?></h5> <div class="image-title"><img src="<?php bloginfo('template_url'); ?>/images/image.png" /></div> <?php endif ?> </div>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, theme development, title, custom header, description" }
strip only specific tags (like <p>), but keep other tags (like <br/>) I know it's easy to disable Wordpress from adding both `p` and `br` tags with: remove_filter( 'the_content', 'wpautop' ); remove_filter( 'the_excerpt', 'wpautop' ); but I want Wordpress to keep adding `<br>` where there is a line break. I only use text editor, visual editor is disabled. It was working fine until the recent update to Wordpress 4.7 - now it is adding some closing `p` tags, without opening them like `</p>` . even tried this plugin but it disables br tags as well. Any way of just disabling `p` tags not `br` tags in post content? I can't find anything on the internet that says something about a solution.
You'd better never disable those actions (what you say). Instead, insert `add_filter('the_content', 'MyFilter', 88 );` and create such function: function MyFilter($content){ $tags = array( 'p', 'span'); /////////////////////////////////////////////////// ///////// HERE INSERT ANY OF BELOW CODE ////////// /////////////////////////////////////////////////// return $content; } # ======== METHOD 1 ========= $content= preg_replace( '#<(' . implode( '|', $tags) . ')(.*|)?>#si', '', $content); $content= preg_replace( '#<\/(' . implode( '|', $tags) . ')>#si', '', $content); # ======== METHOD 2 ====== foreach ($tags as $tag) { $content= preg_replace('#<\s*' . $tag . '[^>]*>.*?<\s*/\s*'. $tag . '>#msi', '', $content); } # ======== METHOD 3 ========= **DOM** object (preferred): <
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "posts, html, wp editor, html editor" }
How To Remove Duplicate Menu Locations I am creating some menus but when I go to the menu dashboard It shows up as "Nice Name" and the 'Menu Name' does anyone know how to prevent this or remove it? I attached photo to illustrate what I mean: ![enter image description here]( I add my menu in my function.php like so: add_action('init', 'register_menus'); function register_menus(){ // This theme uses wp_nav_menu() in one location. register_nav_menus( array( 'primary-nav', __( 'Primary Menu'), 'footer-nav', __( 'Footer Menu') ) ); } The I call it in my header file like so: if(has_nav_menu('primary-nav')){ wp_nav_menu( array( 'theme_location' => 'primary-nav', 'container' => 'nav', ) ); } This has me stumped right now.
You register an array of four menus. If you reformat your code, you will see it. […] array( 'primary-nav', __( 'Primary Menu'), 'footer-nav', __( 'Footer Menu') ); […] Adapt your code to an array with custom keys and you will be fine: […] array( 'primary-nav' => __( 'Primary Menu'), 'footer-nav' => __( 'Footer Menu') ); […]
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions, menus" }
How do you add a link in the description of one section of the customizer to another section in a different panel? I want to add a link like the one that currently exists in the Menu Locations sections of the customizer that says "You can also place menus in widget areas with the Custom Menu widget." The "widget areas" text link automatically opens the Widget panel without refreshing the whole page. How can I duplicate that functionality for whatever section? Here is a screenshot: ![customizer link to widget area](
The relevant line that generates that link in `wp-includes\class-wp-customize-nav-menus.php` is $description .= '<p>' . sprintf( __( 'You can also place menus in <a href="%s">widget areas</a> with the &#8220;Custom Menu&#8221; widget.' ), "javascript:wp.customize.panel( 'widgets' ).focus();" ) . '</p>'; and the more relevant part of it `javascript:wp.customize.panel( 'widgets' ).focus();" )` so it seems like the key for having this kind of functionality is to know the name of the panel... now for sections there is no explicit example in core but might be worth trying to use `javascript:wp.customize.section( 'your section name' ).focus();` as the href of the link
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme customizer" }
Print all the tags from a custom post type I need to print all the tags links which i used in custom post type. Name of Custom post type= mobile Taxonomy tag slug = brand <?php $terms = get_terms( 'brand' ); $count = count( $terms ); if ( $count > 0 ) { echo '<ul>'; foreach ( $terms as $term ) {?> <a href="<?php the_permalink(); ?>"><?php echo '<p>' . $term->name . '</p>';?> </a> <?php } echo '</ul>'; }?> With this code i successfully print all tags name. But unable to make these links. **How to print tags with link to view all post related to that tag??**
To get the link of any term meta, use `get_term_link()` function. < So replace `the_permalink()` to `echo get_term_link($term->term_id);` inside your loop. <a href="<?php echo get_term_link($term->term_id); ?>"><?php echo '<p>' . $term->name . '</p>';?> </a> This link will redirect to tag archive page. Hope this help!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy, tags" }
Is the Wordpress REST API installed and enabled in a vanilla Wordpress 4.7 installation? I've just installed Wordpress 4.7. One of the mentions in the announcement is that it features a REST API. My understanding is: * The Wordpress REST API plugin is not needed anymore, because supposely it has already been merged with core in Wordpress 4.7. * The Wordpress REST API is enabled by default However, I notice that in a vanilla Wordpress 4.7 install, none of the endpoints seems to work (for example ` How can I tell if the new REST API is really activated? Can the REST API be enabled or disabled with the vanilla Wordpress UI, or should I install a third party plugin to do so?
4.7 has it enabled by default. The easy way to check if it is working is just to visit the example.com/wp-json url, and you should get a list of registered end points there There is no official option to disable it as (at least there was a talk about it not sure if it got in the release), some core functionality depends on it. The most obvious things to check for if it is not working is your htaccess rules, and do you have a wp-json directory Also, if `/wp-json/wp/v2/posts` type URLs don't work for you, but `/?rest_route=/wp-json/wp/v2/posts` does, it means you need to enable pretty permalinks in the settings (suggested by Giles Butler in comments below).
stackexchange-wordpress
{ "answer_score": 30, "question_score": 43, "tags": "rest api" }
Category shows only top level child categories I have found this code online but it shows all child categories when on parent category: <?php $this_category = get_category( $cat ); $child_categories = get_categories( array( 'child_of' => $this_category->cat_ID,'depth' => 1)); foreach( $child_categories as $category ) { $category_url = get_category_link( $category->term_id ); $category_name = $category->cat_name; ?> <div class="col3"> <img src="<?php echo z_taxonomy_image_url($category->term_id, array(365, 165)); ?>"> <h3><a href="<?php echo $category_url?>"><?php echo $category_name?></a></h3> </div><?php } For example if I have > > Parent > -Child > --Child 2 > ---Child 3 > Parent 2 > When someone clicks on _Child_ it should show only _Child 2_. This code now shows both _Child 2_ and _Child 3_ when someone clicks _Child_.
`'depth'` is not a parameter for the function `get_categories()`; to get only direct child categories, try working with `'parent'` instead of `'child_of'` < <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories, children" }
Get post id shortcode I'm new at this. I need a shortcode that returns the post id of the post in which the shortcode is inserted. If someone could provide that it would open the doors of understanding for me :) Much appreciated!
Place the below code to your themes `functions.php` or inside your plugin and the `[return_post_id]` shortcode will print the post ID. add_shortcode( 'return_post_id', 'the_dramatist_return_post_id' ); function the_dramatist_return_post_id() { return get_the_ID(); } Hope that helps.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "shortcode" }
php inside HTML via shortcode? Previous two questions of mine lead up to this. Almost there, just need one more nudge :) As a shortcode, I have this form (only problem inputs shown): <input type='hidden' name='item_name' value=<?php echo "'" . get_the_title( get_the_ID() ) . "'"; ?>> <input type='hidden' name='item_number' value=<?php echo """ . get_the_ID() . """; ?>> However the php isn't processing. I think it is in the syntax. Any ideas? Thanks for the patient help!
I think your code should be changed to <input type='hidden' name='item_name' value=<?php echo "'" . get_the_title( get_the_ID() ) . "'"; ?>> <input type='hidden' name='item_number' value=<?php echo "'" . get_the_ID() . "'"; ?>> Based off the first input where you have " ' " and the second one you're using " " " will just return the a string with ". get_the_ID() ."
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "php, forms" }
WP_Query infinite Loop I'm creating a short code to display a table based on a custom post type. For some reason this is creating an infinite loop. Here is the code for the shortcode function cwf_enquiry_table_html() { $args = array( 'post_type' => 'form-enquiry' ); $form_enquiries = new WP_Query($args); if($form_enquiries->have_posts()) { while($form_enquiries->have_posts()) { echo '<p>' . get_the_title() . '</p>'; } } // wp_reset_query(); } add_shortcode('enquiry_table', 'cwf_enquiry_table_html'); Currently this is just returning "Home" constantly. I've got the shortcode on the home page so I presume it's pulling some other query and not the one I am trying to run. As you can see I tried to reset the query but it didn't fix anything.
You need `$form_enquiries->the_post()` to "push" the loop onto the next post \- otherwise yes, you get an infinite loop! while ( $form_enquiries->have_posts() ) { $form_enquiries->the_post(); // rest of your loop }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "wp query" }
Get current category and place it in shortcode <?php echo do_shortcode('[x_recent_posts type="post" count="2" offset="" category="Lisbon" orientation="vertical" no_sticky="true" no_image="false" fade="false"]'); ?> This is the shortcode, and I need to get category name and place it in shortcode. How can I achieve that?
So, you can get the category name with `get_queried_object()->name`: if ( is_category() ) { echo do_shortcode( '[x_recent_posts type="post" count="2" offset="" category="' . get_queried_object()->name . '" orientation="vertical" no_sticky="true" no_image="false" fade="false"]' ); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "shortcode, categories" }
Unable to display Wordpress admin bar in the frontend as an admin I've inherited a Wordpress multisite install. I'm in the process of redesigning several of the subsites and I've noticed that Wordpress is not displaying the admin bar in the front-end, even as an admin. Initially I thought it was a theme error so I went ahead and changed to a stock Wordpress theme such as twenty fifteen. This didn't work. Then I thought it could be a plugin issue so I disabled all plugins as well. This didn't work either. Then I also check if in the user profile I had the show toolbar option enabled, and it is. Wordpress, themes and plugins are up to date. I'm 100% sure it's not a plugin or theme problem, because I am not able to see the admin bar in any of the subsites. Thing is I've ran out of ideas regarding what it could be. Any ideas what could be wrong?
This has to do with the core WordPress functionality when you're working with Multisite and the basic functionality of browser cookies - it's a security issue. The WP core team made the decision to set user login cookies for the admin area to be based on the main multisite install. If you want to be logged in on the sub-sites, then you'll need to log in to each of them individually. It kinda sucks, but it's a bit of a security concern, since WP doesn't know how your multisite is set up, and if they make an assumption about it, then it could be the wrong assumption and therefore opens up a security hole.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp admin, admin bar" }
CSS for menu item added via functions.php I have added a current date item successfully to my menu via functions.php ( **Wordpress 4.7** ) using: add_filter('wp_nav_menu_items','add_todaysdate_in_menu', 10, 2); function add_todaysdate_in_menu( $items, $args ) { if( $args->theme_location == 'header-menu') { $todaysdate = date('l jS F Y'); $items .= '<li class="menu-item">' . $todaysdate . '</li>'; } return $items; } My problem is, that the styling is different to those item added in the wp-admin backend. I have tried a few things according to WP Menu Item CSS Classes, but still got problems with the classes. Help would be great. Thank you very much!
Normally, menu items are rendered as an `<li>` tag with an `<a>` tag inside. You could simply wrap `$todaysdate` in an anchor so that this item will be styled like the others: add_filter('wp_nav_menu_items','add_todaysdate_in_menu', 10, 2); function add_todaysdate_in_menu( $items, $args ) { if( $args->theme_location == 'header-menu') { $todaysdate = date('l jS F Y'); $items .= '<li class="menu-item menu-item-date"><a>' . $todaysdate . '</a></li>'; } return $items; } To keep the item from showing a hand cursor when hovering, add this CSS: .menu-item-date a:hover { cursor: default; /* Other styles for hovered date item */ } Alternatively, you could leave out the `<a>` tag wrapper and create styles for `.menu-item-date` to make this item look like the others, but that might be more work.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions, menus" }
Define a url for an email confirmation from within a plugin I'm making a plugin where the user can order something. But before he has to confirm his email, so I'm sending out that mail with the confirmation link, something like that: `mydomain.com/myconfirmation?token=MYTOKEN` How do I fetch this confirmation url `myconfirmation` in WordPress without the website owner having to create an extra page for this?
Insert in your `functions.php` file the following code function order_confirm_token() { if(isset($_GET['myconfirmation'])) { $confirmation_token = $_GET['myconfirmation']; // Do something with token } } add_action('init', 'order_confirm_token'); Then when you send the user the email to confirm the email direct them to the home page like this: `www.example.com/?myconfirmation=TOKENCODE`
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development" }
PHP Coding Standards, Widgets and Sanitization I have an issue with custom widgets and WordPress Coding Standards. When you create a custom widget, your class should have a "widget" method that will display the widget. Something like: <?php public function widget( $args, $instance ) { echo $args['before_widget']; ?> <span><?php echo esc_html( 'Great widget', 'text-domain' ); ?></span> <?php echo $args['after_widget']; } ?> While this is perfectly functional, this will not pass PHP code sniffer tests with WordPress coding standards because `$args['after_widget'];` and `$args['before_widget'];` are not escaped... What am I doing wrong?
These arguments contain arbitrary HTML and cannot be properly escaped. This is essentially a limitation on how Widgets code was designed and you can see in core Widget classes that no escaping is done on these. Lessons to learn: * WP core doesn't consistently adhere to its own coding standards (and getting there isn't considered worth targeted effort); * passing around chunks of HTML is bad idea, in your own code pass _data_ and render appropriately with proper escaping.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "widgets, escaping, coding standards" }
Can I rename a theme's folder and still receive updates? I'm using a theme that I've pulled from WordPress' repo (example: Twenty Sixteen), the default URL structure looks like so: I want to hide any reference that this WordPress theme is coming from Twenty Sixteen and customize the directory to something else: While I can FTP to my website and rename the folder manually, I noticed that the theme does not receive any updates that are made on WordPress' repo. I'd assume I would create a child theme referring to Twenty Sixteen in order to still receive the latest updates for the theme and still have a custom directory name. Is that the best route?
changing the theme folder I guess it won't affect on updates but changing it's name do. So like you said the best way that every professional company advice is to create a child-theme and modify everything you want on it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "themes, child theme, updates, upgrade" }
Functions For Calling Specific Elements The php functions `get_header()` and `get_footer()` both call the _header.php_ and _footer.php_ files. Could I create a page like _element.php_ and have a function call it (like `get_element()`), where I would have it on the pages that I use that function, but not others, or is this not possible? I searched the documentation, but I don't think I know the official name for what I'm looking for - in essence a function that calls an element for some pages.
It sounds like `get_template_part()` would do the trick. In `element.php` you could simply call `get_template_part( 'element-item' );`, which would then include the `element-item.php` file from your theme. You could wrap this up in a function if you wanted to, e.g. `get_element()`. function get_element() { get_template_part( 'element-item' ); } This approach would allow you to add logic into the `get_element()` function so that it only gets the template part under certain conditions and it would keep the `element.php` template from our example cleaner since the logic would be bundled up in `get_element()`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions, pages, templates" }
Get Image Having the ID My problem is the following: I have a plugin that let people register and upload pictures but... it saves them in a metadata that can t be outputted directly with the short-codes in the plugin. The fact is, the metadata points to the ID of the image. what I need is to understand how to create a short-code that takes an ID of a picture and gives as an output the image. I'm sure its very simple but while I have some experience in making sites on WP I m really bad with the php. Thank you all in advance!
Put the below code in your `functions.php` and then you can use this `[get_image_by_id id="your-image-id"]` shortcode to get the image add_shortcode( 'get_image_by_id', 'the_dramatist_get_image_by_id'); function the_dramatist_get_image_by_id($atts) { return wp_get_attachment_image($atts['id']); } Here `"your-image-id"` is numeric ID of the image. Hope that helps.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, images, shortcode, id" }
Add JavaScript to all WooCommerce Products Does anyone know how to add JavaScript to all WooCommerce products? From what I've read, I might need to upload the code on my server as a .js and then point to it via a function?
If you need to do this on the single product page use this condition then enqueue the JavaScript files. function enqueue_single_product_javascript() { if(is_product()) { // Use wp_enqueue_script() } } add_action('wp_enqueue_scripts', 'enqueue_single_product_javascript'); < <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "javascript, woocommerce offtopic" }
Does WordPress Strip Away the WWW from a Web Address I installed a website and apparently the external DNS all worked fined to access the site: < The problem was that internally, when on their network, they couldn't access the site, which I wasn't sure why as they kept on getting the error: Could not resolve DNS server. Eventually their network guy came back to me and told me that they solved it as apparently WordPress was stripping away the www from their URL. My question is, does WordPress actually strip away the www? If so, do I need to set the Site (URL) to actually be: < as apparently he tells me that this is not ideal practice? I have installed alot of WordPress sites and in the Site (URL), I have never included the www at the beginning. Would appreciate your help.
Wordpress will always redirect to the canonical URL of the content if you try to access a page not with its canonical url. If you installed wordpress without using a `www` then wordpress will assume that the root url for the install is without `www`. Or in other words, wordpress is not actively removing `www`, it is just a by-product of eliminating possibility of duplicate content. As for whether you should use `www` or not, frankly this is the first time in the last 15 years I have heard of anyone that do not treat them the same..... but if he is responsible for your pay check, you can just change the "site url" and "home url" options in the general setting to have `www` and probably nothing more than that.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "site url, dns" }
Override comments.php template with plugin How can I override default theme/WP Core comments.php template with my own in the plugin? I searched for different solutions, but they don't work for me. Or how to hook to the end of any post (even custom post type) to display my custom comments?
The `comments_template` hook: add_filter( 'comments_template', function ( $template ) { return '/absolute/path/to/your/comments.php'; });
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "plugins, plugin development, templates, comments, comments template" }
Icons not showing I'm having a problem with icons not showing in my WordPress site. As you can see in the attached image some of the icons in the admin bar aren't showing. The same is also happening in parts of the theme. See here: < (Look under "Share this product"). Do you know why is this happening? ![Admin bar missing icons](
Thank you @Benoti for pointing me in the right direction. What happened was that I was overriding all font styles with `*{...}` in the theme style.css.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes" }
Trying to create shortcode listing custom posts, but formating not being included I am trying to create my own shortcode I can use to list WooCommerce products. The titles and content display fine, however the html formatting I am trying to use (such as `<strong>` and `<p>`) gets displayed after the title and content instead of with it. `function gr_woo_product_function() { $grcontent; $args = array( 'post_type' => 'product', 'posts_per_page' => 30, 'orderby' => 'ASC' ); $my_query = new WP_Query($args); while ($my_query->have_posts()) : $my_query->the_post(); $grcontent.="<p><strong>".the_title()."</strong><br/>".the_content()."</p>"; endwhile; return $grcontent; } add_shortcode('wooproduct', 'gr_woo_product_function');` Every title should be in bold and every product should have it's own paragraph. But instead each product is listed first and after that there are a bunch of empty paragraphs.
`the_title()` and `the_content()` both include an echo. You want to build a string, so use get_the_title and get_the_content instead.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "posts, wp query, shortcode" }
Call get_template_part() custom permalink How to call `get_template_part()` with custom permalink, I use childTheme from twentytwelve. In my theme I want to call popular post with `get_template_part()`. ex. If I call link http: //domain.com/popular I want to show file `popular.php` (location: childtheme-name/popular.php) please help.
Mapping of URL directly to a template file you describe (mapping URL to a file) is quite rare technique in WordPress, sometimes called _static pages_. It is rare because in general that's not how WordPress works. It works by mapping URL to query variables to WP_Query to template hierarchy to template file. Going from URL to a file skips a lot of mandatory steps. The low key implementation would be to create a page and make your file a custom page template for it. The more direct implementation is also possible, but you would have to both build a custom rewrite rule and implement processing it from scratch.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, get template part" }
Changed from HTTP to HTTP, can login no longer login I changed my whole website to `https` from `http`. Now I can no longer log into my admin area. I always get a redirect loop. I changed my WordPress URL in "General settings" to `https`, how can I solve this problem and how can I manage to log in again?
Sounds like you don't have HTTPS set up correct. To revert back to HTTP and regain access to your admin area, do the following: 1. Go and download Interconnect IT's Database Search & Replace Script here 2. Unzip the file and drop the folder where your WordPress is installed (the root) and rename the folder to **`replace`** (screenshot) 3. Navigate to the new folder you created in your browser (ex: ` and you will see the search/replace tool 4. In the " _search for…_ " and " _replace with…_ " fields: * **Replace** : ` (from HTTPS) * **With** : ` (back to HTTP) You can click the _dry run_ button under _actions_ to see what it will be replacing before you execute the script. Once you're done be sure to remove the `/replace/` folder. Additionally, you can also look into using the Remove HTTP plugin which automatically scans your website and removes both HTTP and HTTPS protocols from your URL links.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "login, https" }
How do I access post_meta key with php? Finally I've managed to achieve what I wanted to do in previous complicated questions :) Sorry for not being clear :/ So now this simple question: I have this div: <div style="display: block;"> content <div> I want to replace "display: block;" with a php statement that checks the post_meta key "buy_status". If there is no such post_meta key, then "display: block"; If the post_meta key exists, and its value is 1, then "display: none"; So what would that php statement be?? Thanks much!
According to docs (< it should be something like: <?php if(!get_post_meta(get_the_ID(), 'buy_status', true)): ?> display: block; <?php else: ?> display: none; <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, html" }
How to insert image into the Settings Page of a Plugin? I'm trying to insert an image from the plugin folder (I've created) so it can be displayed on the Settings Page. * I can't hard code it because the Wordpress doesn't always get installed on the main domain. * I don't want to host the image externally So that leaves me with a way to call the plugins URL using PHP. Does anyone have any ideas how to do this? I'm thinking something along the lines of: <img src="<?php SOMETHING() ?>/plugin_folder/logo.png">
`plugin_dir_url()` "gets the URL (with trailing slash) for the plugin `__FILE__` passed in". <img src="<?php echo plugin_dir_url( __FILE__ ); ?>logo.png">
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php" }
Has is_archived() for sites in a multisite changed with WP 4.7? I have a piece of code displaying a list of sites in my multisite, and I want to exclude the archived ones: $mySites = ( wp_get_sites( $args ) ); foreach ( $mySites as $blog ) { if ( ! ( is_archived($blog) ) ) { switch_to_blog( $blog['blog_id'] ); printf( '%s<a href="%s">%s</a></li>' . "\r\n", $TagLi, home_url(), get_option( 'blogname' ) ); restore_current_blog(); } } Before updating to 4.7, this was working correctly. Now, it doesn't exclude archived sites anymore, it prints out a complete list. Has the function `is_archived()` changed? Or what can the problem be?
Can you try out the following code somewhere and post the output? $mySites = wp_get_sites($args); foreach ($mySites as $blog){ print_r(get_blog_status($blog['blog_id'], 'archived')); } If this works, I suspect the code behind `is_archived()` used to understand blog-objects, but the function is supposed to recieve only the blog ID, not the whole object. Your code should be the following: $mySites = wp_get_sites($args); foreach ($mySites as $blog){ if (!is_archived($blog['blog_id'])){ switch_to_blog( $blog['blog_id'] ); printf( '%s<a href="%s">%s</a></li>' . "\r\n", $TagLi, home_url(), get_option( 'blogname' ) ); restore_current_blog(); } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, multisite, updates, conditional tags" }
Function added to hook "new_to_publish" not executing - custom plugin I was creating a custom plugin which was to send certain emails based on the content/category of a post, but whilst trying to do that, I ran into some problems just getting a basic email sent out. Am I hooking on to the wrong function here? When I publish a post, nothing happens. <?php /** * Plugin Name: Conditional Emailing * Description: Sends emails based on categories. * Version: 1.0 * Author: Ceds */ add_action( 'new_to_publish', 'conditional_email', 10, 0); function conditional_email() { wp_mail('[email protected]','test','test'); } ?> What am I doing wrong here?
You need to add parameters `$old_status` and `$new_status` to the function. function conditional_email( $old_status, $new_status) { wp_mail('[email protected]','test','test'); } You will see that in the example here Hope it works after !
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, posts, hooks, email, publish" }
query_posts based on a meta_key I have custom post type of `brand` and custom field generated via types plugin, `wpcf-sorter` trying to manually create a field to sort my posts. Some of the posts have this custom field populated with a numeric value and others don't have it at all since we're developing this mid-way. My code is: $args = array( 'post_type' => 'brand', 'posts_per_page' => 999, 'meta_key' => 'wpcf-sorter', 'orderby' => 'meta_value_num', 'order' => 'DESC' ); This will pull out all the posts that **have** the `wpcf-sorter` meta key. Is there a way to pull every post and if it has the `wpcf-sorter`, show them first?
This answer is pretty covering for this I think: $args = array( 'post_type' => 'brand', 'posts_per_page' => 999, 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'wpcf-sorter', 'compare' => 'NOT EXISTS', ), array( 'key' => 'wpcf-sorter', 'compare' => 'EXISTS', ), ), 'orderby' => array( 'meta_value' => 'DESC', 'date' => 'DESC' ), ); That should give you all posts with `wpcf-sorter`-value set first, then the rest, both sets ordered by date.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, order" }
Categories vs. Page Site Organization I need to organize the pages on my website so that they appear with the proper hierarchy. The problem is that the category-derived page is appearing outside my hierarchy. This is the current hierarchy if you are on my site today: Home mysite.com -> Internal (page) mysite.com/internal -> Docs (page) mysite.com/internal/docs -> Policy (category) mysite.com/category/policy I need the policy category page to appear under Internal, which is accessible only by my registered users, such as: Home mysite.com -> Internal (page) mysite.com/internal -> Docs (page) mysite.com/internal/docs -> Policy (category) mysite.com/internal/policy I have other (External/Public) category pages that need to be handed differently. Any ideas as to how I can make this happen would be much appreciated.
I switched everything over to a categories model, so that I now have this category hierarchy: Internal -- Docs -- Policy I'll have to figure out how to customize the `/category/internal/` page layout later, but that's lower priority compared to some of the other things on my plate right now. This arrangement meets my immediate needs. **Update** I've finalized the architecture using a 301 redirect for the top-level category page, so that now what I have is this: Internal (category) -- 301 --> Internal (page) -- Docs (category) -- Policy (category)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, pages, slug, hierarchical" }
how improve website mainpage loading I'm using [feed to post RSS Aggregator] and get posts from 44 sites. main page loading is too slow. I checked GTmetrix and it seems good but I don't know how can I improve my website loading. <
Try also different **WordPress caching plugins**. In fact, caching plugins are often very complex. It may be a trouble learning how to use them at first, but it may pay out later. It will take a lot of nerves and lot of coffee, but eventually you will prevail. In theory, it looks easy: ![enter image description here](
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "rss, feed" }
How to edit or override a Core function? I want to add a data argument to links generated by the `paginate_links()` function. Then, I can more easily extend my custom pagination to use AJAX. As far as I can tell, this function is not pluggable, nor does it have any hooks available. The links generated by `paginate_links()` look like this: <a class="page-numbers" href=" class="screen-reader-text">Page </span>2</a> I want to add the data-page argument to the `<a>` tag so it looks like this: <a data-page="2" class="page-numbers" href=" class="screen-reader-text">Page </span>2</a> What would be the best way to edit a Core WordPress function that is not pluggable?
There is no filter, but you can set the `type` argument to `array` when you call `paginate_links()`, and then you can run a filter on the returned array. Example: $links = array_map( function( $link ) { if ( FALSE === strpos( $link, '/page/' ) ) return str_replace( '<a ', '<a data-page="1" ', $link ); return preg_replace( '~<a (.*)/page/(\d+)~', '<a data-page="\\2" \\1/page/\\2', $link ); }, paginate_links( [ 'type' => 'array' ] ) ); print join( ' | ', $links );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "paginate links, core modifications" }
Restrict directory listing to only logged in users I am using directory listing with < theme. Which is obviously not part of WordPress. I am looking for a way to allow only registered subscribers to access + download content from those directories. I have looked into `<?php auth_redirect(); ?>` but it seems like it only works if the page/post is already part of WordPress ecosystem. Is there any way to solve this problem?
You could try configuring your server to pass or “proxy” all requests to your directory through a php script that can check if the user is logged-in. Check out the following answer for an example of how to do this: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "content restriction" }
Trying to make php run in a post I'm trying to make this php code run in a post. Using a plugin to enable the php to run. Problem is I can't seem to get it to work no matter how I structure the statements :/ I'm sure it's something simple but I'm just not familiar enough with php yet to figure it out. Any help would be greatly appreciated :) [insert_php]if(!get_post_meta(get_the_ID()),'buy_status', true); echo "<h5 style="text-align: center;display: block;">"; echo "Sorry, this piece is sold."; else echo "<h5 style="text-align: center;display: none;">"; endif;[/insert_php] </h5>
Here's a solution using a [`[shortcode]`]( which doesn't rely on running PHP inside of the content area. Here are the docs for `get_post_meta()` which show how that function should be called. add_shortcode( 'buy_status', 'wpse249289_buy_status' ); function wpse249289_buy_status( $atts ) { $output = ''; if ( ! get_post_meta( get_the_ID(), 'buy_status', true ) ) { // Post meta value for key buy_status is false $output .= '<h5 style="text-align: center;display: block;">'; $output .= 'Sorry, this piece is sold.'; $output .= '</h5>'; } else { // Post meta value for key buy_status is not false $output .= '<h5 style="text-align: center;display: none;"></h5>'; // Not sure why you'd want to output anything } return $output; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, posts" }
Does anyone have a visual breakdown of core hooks and when they are fired? The title says it all really. I'd like to get an idea of the chronology of when the actions are fired and filters called for WordPress, preferably visually although I'm thinking of downloading, altering core to log to a file whenever an action or filter is registered, then again when fired and working with the output of that. It'd essentially make my life much easier if anyone else has visualised it before.
I completely forgot about this until I was just reviewing my profile. I made a plugin that allows me to log the order of execution whilst debugging complex issues and analysing the content. < It requires PHP7 (or to be more accurate it's tested on 7, 7.1, 7.2) and the 'all' special tag was pointed out by < on reddit. It should be noted that this may require a significant amount of RAM to execute, and will probably slow down a response, so shouldn't be used in production, but the RAW data will help you to understand for a request_uri, given certain specific inputs (logs post and get data), at a given time what hooks were fired, and in what order, function arguments, etc. I found that searching the SQL log table gave me enough data to visualise fully per-request what was going on and when.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 4, "tags": "hooks, core" }
WordPress theme is not displayed properly on other computers I am currently working on making an extranet with WordPress. While I was adding content to the site, I noticed that the theme won't be properly displayed when I visit the page from a Windows 10 machine. This is how the theme looks like from my Debian test machine: < And this is how the Windows 10 machine shows the frontpage: < It looks like the Windows 10 machine only shows the HTML code which results in the theme not being shown as it should. The people I asked for help, said that it had to do with either permalinks or with write permissions. If someone could shed some light on the situation, I would be very grateful.
Are you accessing via an internal IP address? If so, have you set up your wordpress url to be that IP, rather than something like localhost? Wordpress could be creating incorrect links to external files such as CSS etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, wp admin" }
Change sticky status of posts from phpMyAdmin I have many sticky posts in my database. Is there any SQL function which I could use from phpMyAdmin to change (remove) sticky status of posts, if post is sticky to change it to not sicky.
The sticky posts info is stored in the `sticky_posts` option in the options table. It's stored as serialized array e.g. `a:2:{i:0;i:1272;i:1;i:1995;}` You can modify it via the Options API but there's a way to bulk edit posts in the backend: **1\. Select the Sticky view:** ![1]( **2\. Select all sticky posts and apply the bulk Edit action:** ![2]( **3\. Make them non-sticky:** ![3]( and press update.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "sql, sticky post, post status, wp update post, phpmyadmin" }
Display posts with tag for custom post type only I have this is my `functions.php` file to create tags only for custom post type called 'image-gallery': register_taxonomy( 'image-gallery_tags', 'image-gallery', array( 'label' => __( 'Image Tags' ), 'rewrite' => false, 'hierarchical' => false, 'capabilities' => array( 'edit_terms' => 'manage_categories' ) ) ); But I can't get the list of tags to show in the post loop on the front end. I have tried `get_the_tags();` and `get_the_tag_list();` but they will only show tags which are generic to all posts, not the tags for the custom post type. Any help?
`get_the_tags()` is a shortcut function to get the terms from the `post_tags` `taxonomy`. What you have done is make a new and different `taxonomy`. And you will need to use `get_the_terms()` to get your required data. E.g. $terms = get_the_terms($post, 'image-gallery_tags'); <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, custom taxonomy, tags" }
What are some best practices to clean up http mix content warnings? I have a WordPress site with SSL Certificate. Some of my web pages (i.e. ` don't display the green SSL Lock in the address bar but display ` I noticed a bunch of errors due to image files, like in the screenshot below that appear on those pages. What is an easy and fast way to convert all `http` requests to `https`? ![Mixed Content Warning Screenshot]( (source: css-tricks.com)
From your screenshot, it looks like you are displaying images from another website (`nga.gov`), for example: After checking out the links with the mixed content warning, I can see that SSL is set up for this website, which is good. However, their links still default to HTTP, for whatever reason. To fix this on your end, simply change the protocol from ` to ` You shouldn't get a warning once you manually update the links to the HTTPS protocols. Additionally, you can consider using a plugin such as Remove HTTP which strips the protocols from all of your URLs to help fix your mixed content warnings.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "errors, ssl, https" }
Multisite: Activate plugin for subsites only? For some plugins, I'm trying to activate only for subsites. Lets say the plugin is "Contact Form 7" and I need it activated only on subsites. If activate on Network Admin, it will activated on main site as well. _I've came across many reference but it is old article (5 years ago) and only teaching how to make multisite compatible plugin and not subsites-only plugin._
In fact, most of plugins work exactly the way you want: * You MUST upload them (i.e. install them) on network admin panel, but you can leave them deactivated. * Then, you go to an individual subsite plugin page and activate only for said subsite.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "plugins, multisite, activation" }
Display post structure in function I have custom post type : edge, so I built some content by Visual composer. Now I need to display all post type edge in my page. I use the following code in function to get posts but I can not keep the whole site structure by post_content. $args = array('posts_per_page' => -1,'post_type' => 'edge'); $edge_array = get_posts( $args ); foreach($edge_array as $e): echo $e->post_content; endforeach; it display the whole content but not styling like [vc_row][vc_column width="1/2"][vc_column_text] product [/vc_column_text][/vc_column][vc_column width="1/2"][/vc_column][/vc_row][vc_row][vc_column width="1/2"][vc_column_text] I really want it to display exactly in the post with style, is it possible?
Try running the post content through the `do_shortcode()` function before displaying it. $args = array('posts_per_page' => -1,'post_type' => 'edge'); $edge_array = get_posts( $args ); foreach($edge_array as $e): echo do_shortcode($e->post_content); endforeach;
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "posts, customization" }
List categories assigned to a post I want to output the different categories assigned to a post. Let'say for example that a post has three categories: * Downloads * Games * Video Previously I have used `<?php echo get_the_category_list(); ?>` But this wraps the `<a>` in a `<span>` instead of wrapping the `<span>` in a* `<a>`... I want to list the categories like this: <a href="the_URL_of_the_category_downloads"> <span class="the_name_of_the_category_downloads">the_name_of_the_category_downloads</span> </a> <a href="the_URL_of_the_category_games"> <span class="the_name_of_the_category_downloads">the_name_of_the_category_games</span> </a> <a href="the_URL_of_the_category_videos"> <span class="the_name_of_the_category_downloads">the_name_of_the_category_videos</span> </a> I am not sure how I can get this to work with php as I have very limited knowledge of PHP in general.
You can use `get_the_category( )` instead. **Example:** $categories = get_the_category(); foreach( $categories as $category) { $name = $category->name; $category_link = get_category_link( $category->term_id ); echo "<a href='$category_link'> <span class=" . esc_attr( $name) . "></span> </a>"; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, categories" }
WP in Docker - cannot install plugin or upgrade WP For development purpose, I need to setup an installation of WordPress in a docker container. I found and follow this tutorial. Everything is working well, with all the security and optimisation. But the tutorial is based on WordPress 4.5.2. And when everything is setup I cannot upgrade WordPress because of some permission denied. Of course I modified by myself the Dockerfile to get WordPress 4.7 but I will not be able to do the future upgrade. Also if I need to install a plugin, it fail because it cannot create the folder in my volume. If I `mkdir -p` the folders everything is working fine. Here the GitHub with all the files. So I think everything is linked but I cannot fix it. Any idea ?
The problem, as the error description indicates, is permissions. Based on that tutorial, nginx is running under the `www-data` user, but WP folders are owned by `deployer`. If you change the ownership of your $WP_ROOT to www-data:www-data, you will find that you can update your WP. I'm not amazing at security, so there may be a better way, but this one will work to get it updated. In the comment of the tutorial, they made this security change on purpose, so maybe it's not a good idea. Not sure on that level of detail. On top of this change, this update will not persist if you power down the docker instance. You'll have to update your WP instance each time you restart the container. It might make sense to put the WP files into a volume so that WP can update the files as necessary, and that they persist. This would make sense also since the DB persists, and is part of the upgrade anyway. But these decisions on security are above my pay-grade.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 8, "tags": "permissions, docker" }
How do I separate the post title from the content in an excerpt coded thus: We're using a theme for a client that has programmed in their own excerpt & it's alright but it doesn't separate the title from the text in the excerpt itself, which is shown on the blog page. Here's the code: function tt_excerpt( $id, $length = NULL ) { $length = !empty($length) ? $length : 55; $content = apply_filters( 'the_content', get_post_field('post_content', $id)); $content = strip_shortcodes($content); $content = str_replace(']]>', ']]&gt;', $content); $content = strip_tags($content); $content = substr($content, 0, $length); return $content.'...'; } My PHP isn't nearly as strong as my CSS so I'm not entirely certain how to define the title in this excerpt code. I appreciate any insight!
The title isn't mentioned anywhere in that code, have they included it in the actual content? If so, you could remove it using a str_replace: $content = str_replace( get_the_title($id), '', $content);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "title, excerpt, blog page" }
PHP in post content I'm pretty new to Wordpress and I'm a bit stuck. I have created a site and I'm linking to Amazon. I read their ToS and I'm not allowed to hardcode the price in because of price fluctuations. I signed up to the API and got my key and have programmed a function to query the API for the price of an item using the ASIN. This works fine, but when I try to use it in a post it doesn't work. I downloaded the "Insert PHP" plugin so I can use shortcode to call my function and echo out the price. This works partially, but when I echo the returned string it's wrapped in `<p>` tags so I cannot echo it out in a `<h2>` tag properly. How can I get this to work? Is there a way I can echo it out without being wrapped in the `<p>` tags? Thanks
It was a stupid question, I just realized, if I just create a custom shortcode for it, the plugin will not wrap it in `<p>` tags then, or even better still just create it as a plugin of it's own.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php" }
How to debug when error_log not working as expected Trying to debug my development and running into a lot of frustrations with lack of output in the debug.log. For example, I have this defined in wp-config.php: define( 'WP_DEBUG', true ); define( 'WP_DEBUG_LOG', true ); define( 'WP_DEBUG_DISPLAY', false ); ini_set( 'display_errors', 0 ); I have this in my functions.php add_filter( 'the_content', 'my_custom_function' ); function my_custom_function( $content ){ error_log( 'this fired' ); //never works! $return $content; } What am I missing?
After disabling all plugins I was able to narrow down which one was affecting the log output. The client had installed Speed of Light plugin to provide caching and compression which was also effecting wp_debug capabilities.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 4, "tags": "debug, wp debug" }
Get current session in WP admin Trying to access sessions in the WP admin and access a variable from it. function tasks_admin_sessions() { if(!session_id()) { session_start(); } } add_action( 'admin_init', 'tasks_admin_sessions', 1 ); $nonce = $_session['wp_nonce'] $completed_url = admin_url( "post.php?post=$post_id&action=trash&_wpnonce=$nonce" ); but I get: > Notice: Undefined variable: _session What am I missing in my code to get the session variables?
Google is your friend. How to use session_start in Wordpress? and How to use session in wordpress in plugin development It looks like your mistake is that you didn't capitalise "Session" when you declare the variable. Instead of `$_session['wp_nonce']`, try `$_SESSION['wp_nonce']`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp admin, session, admin init" }
Custom posts template page # I want to create a custom template for my job post listing I have registered a new custom post type, `job`. Then I have created a template for a single job post, `single-job.php`, which works fine. But when I enter URL `www.xyz/job` all records are displayed using the `index.php` template which, is the one that my blog uses. How can I create custom template for `www.xyz/job` records so I can edit it independently without touching blog template, which is `index.php`?
A specific post type template could be created with `archive-{post_type}.php` -> `archive-job.php`. Here is a good descriptive image of the template hierarchy in WordPress. ![enter image description here]( Read more about the template hierarchy
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, templates" }
How to use different featured image size for a custom post type? Want to use a different featured image size for a custom post type and exclude it from main blog loop. And also want to display it on specific page. What will be the fastest way to achieve this? With code mess up and plugins? Prefer a code snippet solution, but main issue it should work out-of-box, as fast solution is a priority. Thanks in advance.
This might help - Set featured image size for a custom post type, > Just add a new image size > > > add_image_size( 'companies_thumb', 120, 120, true); > > > Then in the post type template for companies you just call the thumb you defined. > > > <?php the_post_thumbnail('companies_thumb'); ?> >
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "custom post types, post thumbnails" }
How do I convert my WordPress website to be domain agnostic? If my website changes domain or protocol, the entire code base does not have to be updated. That is my desired result. More specifically, I want to add a php function to my child theme to convert all http requests to https automatically. I was given some docs to get started but I realize I have too many questions at this point. Can someone help me out? Cheers BJ < <
Normally you never have to use your domain in your php code for plugins / themes. There are many functions like `get_home_url()` which automatically fetches the domain from configuration and is also protocol agnostic if you don't force a protocol via the third parameter `$scheme`. The function `get_home_url()` internally uses `is_ssl()` and the option value for `home` to decide which protocol to use.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, functions, urls, ssl, domain" }
Check if post exists How can I check if post with name for example Weather exists? If not I want to create it. function such_post_exists($title) { global $wpdb; $p_title = wp_unslash( sanitize_post_field( 'post_title', $title, 0, 'db' ) ); if ( !empty ( $title ) ) { return (int) $wpdb->query("SELECT FROM $wpdb->posts WHERE post_title = $p_title"); } return 0; }
Wordpress has a `post_exists` function that returns the post ID or 0 otherwise. So you can do if ( 0 === post_exists( $title ) ) { **YOUR_CODE_HERE** }
stackexchange-wordpress
{ "answer_score": 9, "question_score": 1, "tags": "posts, query" }
Check if a post has any term in this custom taxonomy? This, if( has_term( 'jazz', 'genre' ) ) { // do something } will check if a post has the term `jazz` from the custom taxonomy `genre`. But how to check if a post belongs to a custom taxonomy `genre`? No matter whatever term it has, as long as it has something from the `genre` taxonomy, it will check. So something like this, if ( has_taxonomy('genre') ) { // whether it's jazz, blues, rock and roll; doesn't matter as long as the post has any of them. }
You can have the term input empty, e.g. if( has_term( '', 'genre' ) ) { // do something } to see if the current post object has any terms in the genre taxonomy. It uses `is_object_in_term()` where: > The given terms are checked against the object’s terms’ term_ids, names and slugs. Terms given as integers will only be checked against the object’s terms’ term_ids. If no terms are given, determines if object is associated with any terms in the given taxonomy.
stackexchange-wordpress
{ "answer_score": 16, "question_score": 9, "tags": "custom taxonomy, taxonomy" }
How to have more than one page for your posts if you have 8 posts but can store max 4 on a page Hello I am new to wordpress and I am creating a custom template. I am sorry if this is simple and has been asked before. I have 8 posts in a page and I have set the page to display a maximum of 4 posts on this page. So my question is how can I create something like arrows which can change from "pageName/1" to "pageName/2" which will display the other 4 posts also known as older posts.
The term you are looking for is Pagination. Placing this code inside the loop should work: <div class="nav-previous alignleft"><?php next_posts_link( 'Older posts' ); ?></div> <div class="nav-next alignright"><?php previous_posts_link( 'Newer posts' ); ?></div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, categories" }
Menu for specific user I'm new in wordpress. I want to hide/show some menus of my main menu according to the user. I mean I want to add some conditions for each menu but I don't know how to do it, if it's possible
Actually I think you need to hide or show the menu items based on **_"User Role"_**. So here a possible solution would be creating menus for each roles and showing them by condition based on **_"User Role"_**. Here is the code- function the_dramatist_menu_change( $args = '' ) { $current_user = wp_get_current_user(); if( in_array('your-user-role', $current_user->roles) ) { $args['menu'] = 'Menu 1'; // Menu name as string } else { $args['menu'] = 'Menu 2'; // Menu name as string } // Add more else if condition based on your user roles. return $args; } add_filter( 'wp_nav_menu_args', 'the_dramatist_menu_change' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "menus" }
Seach and categories not working when ignoring sticky posts in main loop My search does not work anymore, the same goes for my categories. It now shows literally all the posts until the page limit is reached, instead of the specified ones. This happened after I made sure that the sticky posts I show on top of my page are not repeated in the main loop. I added this to my functions.php add_action('pre_get_posts', 'theme_ignore_sticky'); function theme_ignore_sticky($query) { if (is_home() && $query->is_main_query()) $query->set('ignore_sticky_posts', true); } and put this before my main loop in in the index.php query_posts( array( 'post__not_in' => get_option( 'sticky_posts' ), 'paged' => get_query_var( 'paged' ) ) );
I see two issues in your code. First, you pass what could be a string into `post__not_in`, which accepts an array of posts IDs (that's fine if your option holds an array of IDs, but always good to verify). Second, you seem to be repeating the same thing twice: you modify the query with `pre_get_posts` hook, and then you do it again by passing something into `query_posts`. In the documentation (this page, the `posts_per_page` part), they demonstrate the two techniques as _alternatives_ of doing the same thing.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, functions, query posts, sticky post" }
WP CLI allowed fields? Very basic question, but I couldn't find an answer. I am using the WP CLI post get command: < One of the option is [--field=], but I can't find in the doc the list of allowed values for this field. What am I missing?
The list of fields is available on the `wp post list` page. > These fields will be displayed by default for each post: > > > ID > post_title > post_name > post_date > post_status > > > These fields are optionally available: > > > post_author > post_date_gmt > post_content > post_excerpt > comment_status > ping_status > post_password > to_ping > pinged > post_modified > post_modified_gmt > post_content_filtered > post_parent > guid > menu_order > post_type > post_mime_type > comment_count > filter > url >
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp cli" }
Where is the general html template file? I use Wordpress 4.7 and I installed an accessibility module. This module requires pasting the following php code block before the body. I went through the mother-theme php files but didn't find something like html.php or html.tpl ... Should this file be created (and maybe also declared) somewhere? <?php if(function_exists('acp_toolbar') ) { acp_toolbar(); }?>
You should paste that code in the header.php file. Just before the closing code . And that should be done. And if it is asking for pasting the code in the template then find the specific page where you want to place it. There may be different template for different page.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "templates, html" }
Setting Login with User Name and Password default option for Jetpack Admin Login I am working on a new project with Wordpress using the Jetpack plugin. Jetpack add the option to Login using Wordpress Account as the default method of login, if not, then you have to click on a link under to login as traditionally was done with user name and password. Is there a way to flip this.. User name and password be the default and login with Wordpress.com account be the optional second screen?
Edit the `functions.php` in your active theme folder. For me it is `/wp-content/themes/twentytwelve/functions.php`. Add this line to the end of the file: add_filter( 'jetpack_sso_default_to_sso_login', '__return_false' );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "admin, login, plugin jetpack" }
How to keep before/after text inline with nl2br and the_content() I have `"<em><?php echo nl2br(the_content()); ?></em>"` but the two `"` are not inline with the content. How do I keep the before and after `"` characters inline?
You'd want to use `get_the_content()` because `the_content()` echos the output immediately: echo nl2br( '"<em>' . get_the_content() . '</em>"' ); Depending on what the content contains, you still may run into unexpected results, for example, if the content ends with an unordered list. If you want to add the quote marks and `<em>` tags to the content before the standard filters are applied, you can use this approach: echo nl2br( apply_filters( 'the_content', '"<em>' . get_post_field( 'post_content', get_the_ID() ) . '</em>"' ) );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "the content" }
Shows 1400 post published but don't see them I have just imported 1400 post from a XMl document they imported well. But I don't see them in WordPress dashboard. What could be the problem ? ![enter image description here](
Sorry. when I imported a a sql file to wp-post table it has the site link from old site.. So I just replaced these url to the current site using find and replace in notepad++ Now I see all these post
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "import" }
Valid SQL query not returning results I am trying to retrieve some basic information from the Wordpress database for a theme. However, when the query runs it returns no data. If I run the query on Phpmyadmin, it works fine. Note, wp_places_locator is a table used by a third party plugin. function get_info($postid) { global $wpdb; $info = $wpdb->get_results($wpdb->prepare("SELECT post_id, address, phone, email FROM $wpdb->places_locator WHERE post_id = '$postid'")); print_r($info); } Thanks!
Here you've did something wrong with `$wpdb->table_name`. It will only return the default WordPress table names. Not custom table names. And also when you call `$wpdb->prepare` then pass the parameter as array. So your function will be like below- function get_info($postid) { global $wpdb; // Here I assumed that your table name is '{$wpdb->prefix}places_locator' $sql = $wpdb->prepare("SELECT post_id, address, phone, email FROM {$wpdb->prefix}places_locator WHERE post_id = '%d'", array( $postid ) ); $info = $wpdb->get_results($sql); return $info; } Now if you do `print_r` on `get_info()` with parameter post ID then it will return you value. Use like below- print_r(get_info(1)); // Here I assumed your post ID is 1
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, themes, database, sql" }
How to hide the author box of a specific user? I am running a news website, most of the posts are from an Editor Account. I want to hide the author-box displaying at the bottom of the posts, only for this user. Only author box of Editor should be hidden from public. Is there any way to hide the author box of a particular user from public, with a funtion? Author box element is in loop-single.php file. wrapped in the footer of the post, <?php echo $td_mod_single->get_social_sharing_bottom();?> <?php echo $td_mod_single->get_next_prev_posts();?> <?php echo $td_mod_single->get_author_box();?> <?php echo $td_mod_single->get_item_scope_meta();?>
If you know the data of the author, you can wrap that box with an if and the function get_the_author if( get_the_author() == "name_of_the_author" ){ // Don't do it }else{ // Print box } EDIT with the final answer updated: <?php echo $td_mod_single->get_social_sharing_bottom();?> <?php echo $td_mod_single->get_next_prev_posts();?> <?php $user = get_user_by("login", "pknn"); // user object // get_the_author() needs the display name, not the login if( get_the_author() != $user->data->display_name ){ echo $td_mod_single->get_author_box(); } ?> <?php echo $td_mod_single->get_item_scope_meta();?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, author" }
I want to generate the pdf and save it in library? i am using this code to generate pdf $base64_pdf = "data:application/pdf;base64,base64encodedpdf".base64_encode($result); //$base64_pdf = $result; $pdf_base64_handler = fopen($base64_pdf,'r'); $pdf_content = fread ($pdf_base64_handler,filesize($base64_pdf)); fclose ($pdf_base64_handler); //Decode pdf content $pdf_decoded = base64_decode ($pdf_content); //Write data back to pdf file $pdf = fopen ('test.pdf','w'); fwrite ($pdf,$pdf_decoded); //close output file fclose ($pdf); echo $pdf; var_dump($pdf); echo 'Done'; **the output now is** Resource id #617resource(617) of type (Unknown) Done how i can generate the pdf and it save in library
Saving in Wordpress library can be done by using this function media_handle_upload. PDF can be created in many ways. The best method depends on your runtime enviroment and the functionality you are looking for. There are several PDF generating libs for PHP out there, for example PDFlib. But again your question is far broad.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, php, plugin development" }
How is this URL being redirected? I came across this coupon website that uses a URL structure something like the below one for its affiliate links. ` When clicked on the link, it will be automatically redirected from `example.com` to ` I know there are a lot of plugins for WordPress that let you cloak the affiliate links. But those plugins require you to manually add the links in the plugins page first. I was wondering how to achieve the above shown redirect. That is, simply add ` in front of the actual affiliate link and it should be redirected. Is there anyway I can achive this?
You can add `?offers=/ after your link and then check in the destination page (in this case the homepage) if is set `$_GET['offers']`, and in the case that it is, redirect to the content of the var, which is the url. In the Wordpress system I would create a page called "Offers" that would be in `example.com/offers`. You can create a page template attached to this page, and there check if the link sent by get parameters is what you want, and in case it is, redirect the user. A simple page template would be something like this: <?php /* Template Name: Offers */ ?> <?php if(isset($_GET['offers'])){ wp_redirect( $_GET['offers'] ); exit; } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "redirect" }
custom post type by author - wp job manager Hy, I am working with wp job manager, and I would like to list job applications by user, under ultimate member tabs. I have tried using this code, but it shows me all applications function custom_shortcode() { $args = array( 'post_type' => 'job_application', 'author'=>$author_id, ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); the_title(); echo '<div class="entry-content">'; the_content(); echo '</div>'; endwhile; } add_shortcode( 'query_my_posts', 'custom_shortcode' ); Also i have tried this method < But no luck, any help?
As others have stated, you are going to want to add an argument to your shortcode to set a specific author_id. Once you have that you can then perform your query. I have not tested, but the following code should put you on the track. The shortcode would be [query_my_posts author_id="#"] function custom_shortcode() { $atts = shortcode_atts(array( 'author_id' => '', ), $atts); $args = array( 'post_type' => 'job_application', 'author'=> $atts['author_id'], ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); the_title(); echo '<div class="entry-content">'; the_content(); echo '</div>'; endwhile; } add_shortcode( 'query_my_posts', 'custom_shortcode' );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, php, file manager" }
Virtual Composer: How to horizontally align contents from two different columns? First of all, I have never used this site before, so I am not sure if this is the right place to ask this particular question. I am trying to build a website using virtual composer. Right now I have two different columns: the left column contains several icons and the right side contains several pieces of texts. The amount of text blocks is equal to the amount of logos. I am trying to horizontally align each icon with its corrosponding text block, but I can't figure out how to do this. Is there somebody who could help me out?
I'm assuming you have the items in one visual composer row that has two columns. Since the icon heights are probably higher than the default line height, the easiest and in my opinion cleanest solution would be to break each icon & text into separate visual composer rows. You can also nest a row inside of another row in visual composer. (IE: a Parent row that holds all the child rows inside of it.) Once you have the rows all setup, check the settings for the rows. Depending on your version of Visual Composer there might be an option to "align row content". Normally the options for this are "top, middle, bottom".
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "columns, design" }
Problem: wp_query outputs all images on site I'm having issues with a query. I want to get the images attached to an individual post of the type _rental_. My query is broken as it outputs all the images on the entire site: $image_query = new WP_Query( array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_mime_type' => 'image', 'posts_per_page' => -1, 'post_parent' => $rental->post->ID, 'order' => 'DESC' ) ); if( $image_query->have_posts() ){ while( $image_query->have_posts() ) { $image_query->the_post(); $imgurl = wp_get_attachment_url( get_the_ID() ); echo '<div class="item">'; echo '<img src="'.$imgurl.'">'; echo '</div>'; } wp_reset_postdata(); } Any ideas on how I can adjust this to only get the images attached to the current post?
Your issue is the `post_parent` parameter, if this is set to 0 or a falsey value like null your query will return all top level posts. So you just have to make sure $rental->post->ID has a value, or use a different approach like the `get_the_ID()` function. Can't really tell you more than that as you have not included the part where you set `$rental` $image_query = new WP_Query( array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'posts_per_page' => -1, 'post_parent' => get_the_ID(), // your issue here lays ) ); And check out the docs for more details: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, wp query, loop, images" }
How to load file only in single post page through function.php? I want to include a file only in single post page. I've following code but not working; if (is_single()){ require_once(dirname(__FILE__) . '/inc/lazy-load.php'); } I mean i just want to load lazy-load in only single post page. but above code is not working. Any idea? Hope to get a solve for this problem.
is_single function checks for $wp_query global variable is loading single post of any post type or not , $wp_query is set after running query_posts function that loaded after wp action hook. So you should call this function in the right order ( hook ) add_action( 'wp', 'include_single_lazy_load' ); function include_single_lazy_load() { if( is_single() ) { require_once(dirname(__FILE__) . '/inc/lazy-load.php'); } }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "uploads" }
Do I need to re-import Susy to work with it in a child theme? I'm sure this is a question with a simple answer. I am working on a Storefront child theme. Storefront's stylesheet has been compiled using the Susy grid system - and I was hoping to inherit mixins etc. based on the parent's definitions, but all the Sass partials are present in the parent theme's Assets folder except for Susy (and Bourbon, which I'd like to use too). Do I need to re-import/re-declare these libraries if I want to use them?
Since Sass is pre-compiled, you will need to import it in each stylesheet that you compile. This means that you will need to re-import it in your child theme stylesheet since it is independent of the parent theme stylesheet.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, child theme, sass" }
Accessing Custom Fields on Pages I'm wondering how to get at custom field information attached to a page, not a post. Using get_post_meta seems like the right idea, but I don't know how to tell the function to look at page ids and not post ids. Also it's no clear to me if this function can work outside the loop. A short piece of code showing how to access the page custom field would be really useful.
Sometimes WordPress is criticized treating everything as a `post`. The matter of fact is, post type `pages`, post type `post` \- both are actually Post in database. So no post will collide with any page ID. :) So simply a `get_post_meta()` is enough. But if you still want something specific to Pages, you can use: if( is_page() ) get_post_meta(...); Yes, you can use `get_post_meta()` outside the loop. But instead of passing the post_id using `get_the_ID()` you have to pass the post_id manually.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field" }
How do i remove animated icon Hey so i have adriana theme and there are these three animated icons that are on the page and i want to remove them. and after removing the icons i want the three paragraphs in brown to stay in that order but just move up where the icons used to be. PLease help how would i do this i have no idea.
Probably your theme might have an option for making the icons hidden. In case it hasn't a specific option for that, you could achieve what you want with CSS in order to control your website's styles. Most modern themes have a custom css option under their settings so you can set place your custom css styles. Search for that kind of option, place the following there and Save changes. .home-title.i-container { display: none !important; } The above would hide the animated icon element through the whole website. In case you want to hide the icons only on your home page, use the following instead: .home .home-title.i-container { display: none !important; } If you can't find an option for placing custom css code through your theme's settings, you have to manually edit your theme's main style.css file and re-upload it to your server.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "customization" }
Theme and plugin install or update display error in localhost Theme and plugin install or update display error in localhost **"connection information error"** in localhost how to connect the **FTP** ![enter image description here]( I'm using wordpress 4.7
The install wordpress in the localhost Copy the code **wp-config.php** file.. To add the this code in **wp-config.php** file `define('FS_METHOD', 'direct');` Avoid the asking **"connection information error"**
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, themes, updates, installation" }
Remove the last X characters of a custom field value This snippet shows us how to remove 3 characters at the end of a string... echo substr($string, 0, -3); I'd like to find a way to use a custom field value as the string. This is what I've tried with no luck... echo substr( get_post_meta( $post->ID, "CUSTOMFIELD", true ), 0, -3 );
You have to consider that you're dealing with `substr()` a _string_ related function as the **str** in the function name indicates. That does mean that the parameter `$string` you give actually has to be of the type `string`. `get_post_meta()` on the other hand does just give you back whatever type you saved in the first place. So it isn't guaranteed that your getting back a string - you have to make sure of that yourself. Which you can do by type casting the value, variable you receive. So far so good, let's put it together: $custom_field = (string) get_post_meta( $post->ID, "CUSTOMFIELD", true ); echo substr( $custom_field, 0, -3 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, custom field" }
functions.php mistakenly deleted I've mistakenly deleted the **`functions.php`** file of my Twenty Sixteen WordPress Theme running the command below: rm /var/www/html/wp/wp-content/themes/twentysixteen/functions.php The Twenty Sixteen Theme is my currently active theme and as such, my WordPress site is no longer accessible as it used to be _(ref. screenshot below)_. ![enter image description here]( How do I fix it?
To fix your site, you should get another **`functions.php`**. As such, you can get that from your most recent and operational backup and upload it unto the location of the mistakenly deleted one. In case you don't have a backup, your last option will be to download a fresh copy of your theme; once that done, extract and upload the **`functions.php`** file it contains unto the location of the one you've mistakenly deleted from your server. In the later case (should you have edited directly your **`functions.php`** \- _which is not a recommended practice_ ), you cannot recover any previous modifications performed on the file. _Should you consider editing the Twenty Sixteen WordPress Theme or any other one from theWordPress Repository or any other source, I will recommend you create a Child Theme of the theme you intended to use for that purpose, rather than editing the actual theme directly._
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, themes" }
Showing All Media from All Multisites Is there a way to have a "Media" page that shows all media from all multisites? I am the admin/owner of a multisite, and wish to ensure that all media uploaded by susbsites is appropriate for those sites. And I need to edit images occasionally - mostly to rotate them for each subsite client. Ultimiately, it would work like the standard Media page. Although there is a plugin that shows subsite media, it only shows one subsite at a time. I am looking for a more 'global' media page. Thanks..
After posting the question, I did a ton of googles, and eventually built a plugin that displays all media for all subsites in a multisite installation. If the user is SuperAdmin, each picture is linked to it's editing page. The plugin is called 'Multiside Media Display', and available via the usual Add Plugins page in WP Admin. (Unfortunately, the plugin will not install via the Install button; that results in a 'Installation failed: The package could not be installed.' error....for which I am puzzled, and have posted a question about here). But it will install if you download/install locally. And then you can look at the code to see how it is done (too much code to display here). The code includes links to info I found about the various processes used. So, solution available (once I get past the install problem).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, media" }
Conditional/Check: IF author has no First Name THEN I'm looking to find a way to check if the author has included their first name (at registration) and if they haven't then do something... I have no idea where to start, or finish, but I assume it looks a little like this??? <?php if (get_the_author_meta('first_name', true)) { ?> // do something <?php } ?>
The second parameter for `get_the_author_meta` is the user iD. If you're using the function within the loop, the user ID would be the ID of the current user if not you would have to specify the user ID. if ( !get_the_author_meta('first_name', $user_id )) { // do something }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "author, conditional content" }
Conditional/Check: IF comment author is the post author I'm trying to edit my comments.php so that I can conditionally display `//do something` if the comment author is also the post author. I have no idea what I'm doing but I've managed to throw this piece of garbage together as a start (what a joke)... <?php if ( get_comment_author(global $wp_get_current_commenter(); wp_get_current_commenter() && $wp_get_current_commenter()->ID && == $post->post_author)) { ?> // do something <?php } ?> I've read this link but it's no more clear to me.
<?php if ( $post = get_post($post_id) ) : ?> <?php if ( $comment->user_id === $post->post_author ) :?> //do something <?php endif;?> <?php endif;?> Also. <?php global $post; if( $comment->user_id === $post->post_author ) { // do something } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "author, comment form" }
How to loop through yoast primary categories? Is there any way I can edit the below so that it will only get posts from the category if the post has been assigned as the primary category that Yoast SEO adds? I only want to get posts that have been assigned to this category and that it has been marked as the primary category. <?php $args = array( 'posts_per_page' => 6, 'offset' => 0, 'orderby' => 'date', 'order' => 'DESC', 'post_type' => 'post', 'post_status' => 'publish', 'suppress_filters' => true, 'tax_query' => array( array( 'taxonomy' => 'news-category', 'field' => 'slug', 'terms' => 'offers' ) ) ); $posts = get_posts( $args );
Managed to sort it, the primary category is added as post meta to the post, therefore you can pass through the following arguments: 'meta_key' => '_yoast_wpseo_primary_news-category', 'meta_value' => 1179, Note: your meta key will be different since this is a custom taxonomy that I have set up, if you print the get_post_meta for your posts, you should be able to see what the meta key is...
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "loop, plugin wp seo yoast" }
2 custom posts types, in their own columns, one pagination for both I have a page template has 2 columns. Each column has a loop for a single custom post type, with pagination. The pagination links work for both columns, when you click any number it will take you to the page# for BOTH post types (there's a "sorry no more posts" message if one post type runs out of posts) I want to maintain this functionality, but combine the pagination into only 1 section that checks the total number of posts for BOTH post types and creates the links based on that number, rather than having 2 separate link lists below each column. How can I combine the pagination from these 2 loops OR combine the master loop but still break the posts into 2 columns, by post type? I have already tried a few things 1. 1 loop, 2 post types (do not know how to break this into 2 columns) < 2. 2 loops, 2 columns, 2 paginations < thanks!
re 2. two loops, one pagination link: remove the individual paginations; add this at the end: $max = max($ideas_query->max_num_pages,$opinions_query->max_num_pages); if (function_exists('custom_pagination')) { custom_pagination($max,"",$paged); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, theme development, loop, pagination" }
How to rename the plugin PHP file without affecting existent users? A plugin of mine has main PHP file named "init.php", now I want to follow best practice and rename it to "plugin-name.php" As users are used to upgrade the plugin by overwriting the old folder with update, so there will be init.php plugin-name.php both exist in the plugin folder after upgrade, which results in a PHP fatal error, saying a class not found, whatever, deleting "init.php" and all clear. Though I can tell users how to fix it when they contact me, but it isn't a good solution to throw the error on users, is there a way to remove or ignore legacy main plugin file in WordPress?
Depending on the plugin version delete the file `init.php` on upgrading from the plugin folder. For this purpose you can use the Filesystem API, especially the `delete()` method \- here exemplary linked to the `WP_Filesystem_Direct` class.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development" }
How do I pull post from standard post format? I use this code to take a post from the post format. $query = array( 'showposts' => 5, 'post_type' => 'post', 'tax_query' => array( 'relation' => 'OR', array( 'taxonomy' => 'post_format', 'field' => 'slug', 'terms' => array( 'post-format-video' ) ), ), ); array( 'post-format-standard' ) is not. How do I pull from standard format ? Thanks so much.
The `terms` parameter will only accept custom post types and, like you mentioned, `post-format-standard` is not one. Try instead to use the 'NOT IN' operator to test against the custom posts you don't want to display (all in this case): $query = array( 'showposts' => 5, 'post_type' => 'post', 'tax_query' => array( 'relation' => 'OR', // You likely don't need this array( 'taxonomy' => 'post_format', 'field' => 'slug', 'terms' => array( 'post-format-video', 'post-format-image', 'post-format-link', 'post-format-aside', 'post-format-quote', 'post-format-chat', 'post-format-video', 'post-format-chat', 'post-format-audio' ), 'operator' => 'NOT IN' ), ), ); The thinking here is that it won't display anything but standard posts. Reference Taxonomy_Parameters
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "array" }
Get array of shortcodes within string I do have an post/page where the shortcode "question" occurs many times. What is the best way to get an array of all the "question" shortcodes with their related parms? [question a=1 b=2 c=3 ] [question b=2 c=3 ] [question a=1 b=2 ] [question]
function wpse250308_get_questions() { global $post; if ( preg_match_all('/\[question(.*?)\]/', $post->post_content, $questions ) ) { $questions = array_key_exists( 1 , $questions) ? $questions[1] : array(); // $questions will contain the array of the question shortcodes //Do your stuff } } `$post` isn't available before `wp`. So, you have to hook on it or actions that fires later.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode, regex" }
Why "Contact Form 7" doesn't update PHPmailer library? I realized that popular Wordpress plugin `Contact Form 7` uses this library < When I check source of mail, which has been sended from Contact Form 7, it looks like this: X-Mailer: PHPMailer 5.2.14 ( X-WPCF7-Content-Type: text/plain So, this version is from (Nov 1st 2015). < The latests one is: > Version 5.2.18 (December 24th 2016) > > **SECURITY** Critical security update for CVE-2016-10033 please update now! Thanks to Dawid Golunski. Why Contact Form 7 uses old versions of PHPMailer?
PHPMailer is not part of the plugin, it is shipped with WordPress. So it is up to WordPress to keep it up to date. There is a patch already in ticket #37210. In the mean time, you can create a mu-plugin, include the newer version of PHPMailer here, create an instance and assign it to the global variable `$phpmailer`. WordPress will then use _that_ instead of its own outdated version. But be aware that WordPress’ version has some changes that are not compatible with the original class, so you might break some plugins.
stackexchange-wordpress
{ "answer_score": 10, "question_score": 7, "tags": "plugins, security, updates, plugin contact form 7, phpmailer" }
How do I properly code my footer? See example I would like to code this footer code: <p class="mh-copyright"><?php printf(esc_html__('Copyright &copy; %1$s | Made by %2$s', 'mh-magazine-lite'), date("Y"), '<a href="' . esc_url(' . '" rel="nofollow">Dev</a>'); ?></p> So my footer will look something like this (plus Terms of Use and Privacy Policy has hyperlink with "_blank" target in them): Copyright © 2016 | Made by Dev | Privacy Policy Terms of Use
you can use this code in the footer ... <div class="your-class-name"> <?php _e('Copyright &copy ', 'textdomain'); ?> <?php echo date('Y'); ?> | <?php _e('Made by Dev ', 'textdomain'); ?>| <a href="#"><?php _e('Privacy Policy Terms of Use', 'textdomain'); ?></a> </div>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, footer, copyright" }
Check if post with same meta value exists I'm building a phone numbers directory website. Using `wp_insert_post()` visitors are allowed to add phone numbers without having to register or log in. There's a custom post type called "numbers" and phone numbers are stored in custom posts' meta values. Here's the code: `$post_id = wp_insert_post(array ( 'post_type' => 'numbers', 'post_title' => $name, 'post_content' => $details, 'post_status' => 'draft', 'tax_input' => $custom_tax, )); if ($post_id) { // insert post meta add_post_meta($post_id, 'number', $number); }` I don't want my users to add the numbers that have already been added before. I need to somehow check if the entered phone number already exists in any post's meta value or not. If number already exists in database, user shouldn't be allowed to add it.
Try below code. $args = array( 'fields' => 'ids', 'post_type' => 'numbers', 'meta_query' => array( array( 'key' => 'number', 'value' => $number ) ) ); $my_query = new WP_Query( $args ); if( empty($my_query->have_posts()) ) { $post_id = wp_insert_post(array ( 'post_type' => 'numbers', 'post_title' => $name, 'post_content' => $details, 'post_status' => 'draft', 'tax_input' => $custom_tax, )); if ($post_id) { // insert post meta add_post_meta($post_id, 'number', $number); } } If there is same number in postmeta it will not allow to create post and post meta. Hope this will helps you.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, custom field, post meta" }
Putting hyperlinked and non-hyperlinked text in one line, centered, on .php My code for my footer is: <?php echo "<font color=#ffffff>Copyright © 2016 EXAMPLE |</font></p>"; ?> <?php echo "<a href=privacy-policy><font color=#0080ff>Privacy Policy</font></a></p>"; ?> <?php "<font color=#ffffff> / </font>"; ?> <?php echo "<a href=terms-of-use><font color=#0080ff> Terms of Use</font></a>"; ?> I want it to look like this (centered): Copyright © 2016 EXAMPLE | Privacy Policy | Terms of Use if the vertical bar can't be used there, you can suggest. Thanks.
This isn't really a WordPress specific question but here's what you'll likely want to do. Notice also the example below is using the PHP `date` function which will dynamically update the year: **style.css** .copyright { color: #ffffff; display: table; margin: 0 auto; } .copyright a { color: #0080ff; } **footer.php** <div class="copyright"> Copyright &copy; <?php echo date('Y'); ?> EXAMPLE | <a href="#">Privacy Policy</a> | <a href="#">Terms of Use</a> </div>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php" }
Improving the readibility of bright text on a bright background I' im interested in improving the readibility of a bright text on a background which is partially bright. I think the readibility would improve if one could create a dark border around the text. Is that possible in WordPress? Or does somebody of you have another proposal how to solve this problem? The site I' m referring to: www.sabertec.net Readability problems especially on: www.sabertec.net/news/ Greetings, Peter123.
A simple way of increasing the contrast for the letters is to add a drop shadow to them. Use `text-shadow` in CSS for that: .entry-content p { text-shadow: 1px 1px 2px #000000; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css" }
Forced Redirect on a server migration I have backedup and installed my site on a new server underneath the new domain of After the DB and file transfer I logged in and immediately got a 500 error. I then overwrote the `.htaccess` file to the default and renamed the plugin folder to `plugins-rename` and then tested again. Now the site resolves, but then automatically redirects the browser to I also forced the site to exist under it's new old.example.com within the WP-config file using the following commands define('WP_HOME',' define('WP_SITEURL',' Any ideas where this redirection might exist as it can't be contained within a plugin so must be somewhere else?
Here's a clean and sure way that I follow when I migrate a WordPress to a new domain (or subdomain): 1. Go and download Interconnect IT's Database Search & Replace Script here 2. Unzip the file and drop the folder where your WordPress is installed (the root) and rename the folder to **`replace`** (screenshot) 3. Navigate to the new folder you created in your browser (ex: ` and you will see the search/replace tool 4. In the " _search for…_ " and " _replace with…_ " fields: * **Replace** : ` (old domain) * **With** : ` (new domain) You can click the _dry run_ button under _actions_ to see what it will be replacing before you execute the script. Once you're done be sure to remove the `/replace/` folder.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "redirect, migration" }
Wordpress theme options Menu I am struggling from last 1 Hour couldn't find why the menu is not appearing WordPress admin. <?php function wpt_add_theme_page() { add_theme_page( __('Theme Options','wpsettings'), __('Theme Options','wpsettings'), 'edit_theme_options', 'wptsettings', 'wpt_theme_options_page' ); } function wpt_theme_options_page() { echo "Hello"; } /*---------------------------------------*/ /* Enqueue Theme Styles */ /*---------------------------------------*/ function wpt_theme_styles() { wp_enqueue_style( 'main_css', get_template_directory_uri() . '/style.css' ); } add_action( 'wp_enqueue_scripts', 'wpt_theme_styles' ); ?> Is there any syntax error that I couldn't find?
You need to hook your function to the `admin_menu` action: add_action( 'admin_menu', 'wpt_add_theme_page' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development, admin menu, settings api" }
Only displaying zip files with wp media I'm using `wp.media()` to invoke the WordPress media library modal in a custom taxonomy. In the pop up I only want to display zip files. I know I can limit the media library to just audio or video using those keywords but there doesn't seem to be a comprehensive list of "types" anywhere. How would I get `wp.media()` to only display zip files? Currently I have: // Sets up the media library frame meta_image_frame = wp.media.frames.meta_image_frame = wp.media({ title: meta_term_image.title, button: { text: meta_term_image.button }, library: { type: "zip"} }); Needless to say `type: "zip"` doesn't work. However `type: "audio"` works just fine.
The zip files are in a subtype called `application` so you should try using: `type: 'application/zip'` A list of default allowed mime types is available from wp_get_mime_types.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "javascript, media, media library, media modal" }
How to Navigate within Category? Lot of codes here on stackexchange didn't work At present I am using the below code to navigate between previous and next post. <?php global $wp_query; if (is_single()) { ?> <div class="prev-navigation"> <?php previous_post_link('%link', '&Lang; &Lang; &Lang; %title') ?> </div> <div class="next-navigation"> <?php next_post_link('%link', '%title &Rang; &Rang; &Rang;') ?> </div> <?php } ?> You can check this code at work on www.pmfias.com
Both **`previous_post_link`** and **`next_post_link`** accept a 3rd boolean parameter **$in_same_term** , which specifies whether link should be in a same taxonomy term. So in your scenario you would be looking to make the following update: **previous_post_link** <?php previous_post_link('%link', '&Lang; &Lang; &Lang; %title') ?> **updated to** <?php previous_post_link('%link', '&Lang; &Lang; &Lang; %title', true) ?> **andnext_post_link** <?php next_post_link('%link', '%title &Rang; &Rang; &Rang;') ?> **updated to** <?php next_post_link('%link', '%title &Rang; &Rang; &Rang;', true) ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "next post link, previous post link" }
Set multisite settings when new site created I need to set some defaults for my multisite sites as they are created but It's not quite working. I have this in the `install.php` file in `/wp-content`: function wporg_wpmu_new_blog( $blog_id, $user_id, $domain, $path, $site_id, $meta ) { update_blog_option( $blog_id, 'upload_url_path', ' ); update_blog_option( $blog_id, 'upload_path', '/home/www/myfiles/newsite' ); update_blog_option( $blog_id, 'blog_public', '0' ); switch_to_blog($blog_id); // Remove the default post & page wp_delete_post(1, true); wp_delete_post(2, true); // Remove the first comment wp_delete_comment( 1, true ); restore_current_blog(); } add_action( 'wpmu_new_blog', 'wporg_wpmu_new_blog', 10, 6 ); Am I missing anything?
`install.php` is only run during **installation** , it wont be run during new site creation. You'd need to put that code in a mu-plugin to have any chance of running. (I guess it could also exist in a network-activated plugin, but I'm not 100% sure of that) Add the following before your code, and put your file in `wp-content/mu-plugins`: <?php /* Plugin Name: Yourmultisite options Description: Foobar Version: 1.0.0 Author: You Author URI: */
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "multisite" }
Select dropdown with 2 choices from foreach I have a problem. I need to list only 2 roles: customer and shop_manager. 1. How can i do that with this script? add_action( 'register_form', 'myplugin_register_form' ); function myplugin_register_form() { global $wp_roles; echo '<select name="role" class="input">'; foreach ( $wp_roles->roles as $key=>$value ): echo '<option value="'.$key.'">'.$value['name'].'</option>'; endforeach; echo '</select>'; }
You can use **in_array** to check if the name of the role is either customer or shop_manager add_action('register_form', 'myplugin_register_form'); function myplugin_register_form() { global $wp_roles; echo '<select name="role" class="input">'; foreach ($wp_roles->roles as $key => $value): if ( in_array( $key, array('customer', 'shop_manager') ) ) echo '<option value="' . $key . '">' . $value['name'] . '</option>'; endforeach; echo '</select>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user roles, user registration, php" }
301 Rewriting htaccess I have list of url's to redirect using htaccess. from my OLD domain to New domain. i have done this in my htaccess RewriteEngine on RewriteCond %{HTTP_HOST} !^sub.domain1.com$ RewriteRule ^(.*)$ [R=301,L] RewriteEngine on RewriteCond %{HTTP_HOST} !^sub.domain1.com$ RewriteRule ^(.*)$ [R=301,L] redirection working fine, But i want something like ` to ` and i did this. RewriteEngine on RewriteCond %{HTTP_HOST} !^sub.domain1.com/old-page/$ RewriteRule ^(.*)$ [R=301,L] and the url is ` please help
Try this: RewriteEngine on RewriteRule ^old-page/(.*)$ [R=301,L] Works on my test.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "url rewriting, redirect, htaccess" }
How do I enable the text editer in my WordPress theme? My text editor seems to be broken. I can reproduce this issue on cPanel. I clean-installed everything 2-3x and this issue still persists. I wasn't able to reproduce it on Managed WordPress. I am using the latest version of WordPress and OnePress (theme). Steps 1\. Install and activate OnePress demo theme in WordPress 2\. Go to Dashboard 3\. Click Appearance in the left-hand menu 4\. Click Customize 5\. Click Section: About 6\. Click Section Settings 7\. Attempt to edit text in Section Description Result: Unable to add text in all "Section Description" fields for all sections' See result screenshot Expected Result: Text editor is disabled; see expected_results screenshot
Fixed. Steps 1\. Go to WordPress dashboard 2\. Click on username at the top bar 3\. Click "Edit My Profile" 4\. Uncheck "Disable the visual editor when writing" 5\. Scroll to the bottom and click "Update Profile"
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, custom field, uploads, text" }