qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
273,844
<p>How do I add a custom post type to what I'm assuming is a table in WP's underlying database.</p> <p>I.e. I don't want to have this loading on every page and I want to be able to use slug and post-type queries on it.</p> <pre><code>function cptui_register_my_cpts_app() { $labels = array(); $args = array(); register_post_type( "app", $args ); } add_action( 'init', 'cptui_register_my_cpts_app' ); </code></pre> <p>More specifically, I want to be able to create a redirect from a custom post type (in this case 'app') to the login page if members are not already logged in.</p> <pre><code>function my_redirect() { if( !is_user_logged_in() &amp;&amp; is_singular('app') ) { wp_redirect( 'login page' ); exit(); } } add_action('init', 'my_redirect'); </code></pre>
[ { "answer_id": 273828, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": 0, "selected": false, "text": "<p>Your function <code>get_instance</code> will never create an instance of the class because of ...
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273844", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124145/" ]
How do I add a custom post type to what I'm assuming is a table in WP's underlying database. I.e. I don't want to have this loading on every page and I want to be able to use slug and post-type queries on it. ``` function cptui_register_my_cpts_app() { $labels = array(); $args = array(); register_post_type( "app", $args ); } add_action( 'init', 'cptui_register_my_cpts_app' ); ``` More specifically, I want to be able to create a redirect from a custom post type (in this case 'app') to the login page if members are not already logged in. ``` function my_redirect() { if( !is_user_logged_in() && is_singular('app') ) { wp_redirect( 'login page' ); exit(); } } add_action('init', 'my_redirect'); ```
You are just doing it wrong. The problem starts with using a singleton, just never do it. You have a class of loggers which logs into some internal buffer. All loggers log into the same buffer, therefor the buffer (`trace` in your case) a static array in the class. No more `get_intance`, just instantiate a new logger and log. This gives you the added flexibility of having several classes of loggers that "output" to the same buffer. We are left with a question of how to inspect the log, and this you do with a static method. I am sure this scheme can be improved by people that are more hard core OOP than me, using singleton is equivalent to using a `namespace` and code written under a namespace is easier to read and use than the singleton, just call a function directly with no need to handle the complications of getting an object first, it is easier to use a function in a hook, etc.
273,870
<p>I have develop a wordpress website consulting and I have different user role </p> <p>and I want to have different content according to user role </p> <p>so I have a landing page with authentification and according the user role login , the homepage is different </p> <p>so I would like to say if plugin who make something like this exist or if can code for that</p> <p>so recap :</p> <p>Home page for not login is landing page home page for user login is different according to user role </p> <p>Thanks !</p>
[ { "answer_id": 273872, "author": "danbrellis", "author_id": 34540, "author_profile": "https://wordpress.stackexchange.com/users/34540", "pm_score": 1, "selected": false, "text": "<p>Two options come to mind. Which one will depend on how different your content is for logged in/not logged ...
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273870", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124159/" ]
I have develop a wordpress website consulting and I have different user role and I want to have different content according to user role so I have a landing page with authentification and according the user role login , the homepage is different so I would like to say if plugin who make something like this exist or if can code for that so recap : Home page for not login is landing page home page for user login is different according to user role Thanks !
To use a different page's content on the homepage based on a logged-in user's role you can do this: In your functions.php file add this code: ``` function wpse_273872_pre_get_posts( $query ) { if ( $query->is_main_query() && is_user_logged_in() ) { //work-around for using is_front_page() in pre_get_posts //known bug in WP tracked by https://core.trac.wordpress.org/ticket/21790 $front_page_id = get_option('page_on_front'); $current_page_id = $query->get('page_id'); $is_static_front_page = 'page' == get_option('show_on_front'); if ($is_static_front_page && $front_page_id == $current_page_id) { $current_user = wp_get_current_user(); $user = new WP_User($current_user->ID); if (in_array('cs_candidate', $user->roles)) { //assuming the role name is cs_candidate $query->set('page_id', [page-id-for-candidate-homepage]); } elseif (in_array('cs_employer', $user->roles)) { //assuming the role name is cs_employer $query->set('page_id', [page-id-for-employer-homepage]); } } } } add_action( 'pre_get_posts', 'wpse_273872_pre_get_posts' ); ``` What this does is: 1. Filters the wp\_query args if a user is logged in, you're on the homepage and it's the main query 2. If the user has the role 'candidate', set the post id (p) to the ID of the page you created and change the post\_type to 'page' 3. Similarily, if the user has a role employer, use the ID for that page. Thanks for helping clarify all your points.
273,878
<p>I created some code to return attachment categories, that looks like:</p> <pre><code>&lt;?php // Attachment Categories $categories = get_the_category($attachment-&gt;ID); if ($categories) { ?&gt; &lt;ul&gt; &lt;?php foreach ($categories as $category) { ?&gt; &lt;?php if ($category-&gt;name !== 'Slides') if ($category-&gt;name !== 'Uncategorized') { ?&gt; &lt;li&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/li&gt; &lt;?php } ?&gt; &lt;?php } ?&gt; &lt;/ul&gt; &lt;?php } ?&gt; </code></pre> <p>I am trying to add an <code>else</code>, but for some reason the else doesn't work with the two <code>if</code> statements...if I remove one <code>if</code> statement, the <code>else</code> works.</p> <p>The code with the <code>else</code> looks like:</p> <pre><code>&lt;ul&gt; &lt;?php foreach ($categories as $category) { ?&gt; &lt;?php if ($category-&gt;name !== 'Slides') if ($category-&gt;name !== 'Uncategorized') { ?&gt; &lt;li&gt;&lt;?php echo $category-&gt;name; ?&gt;&lt;/li&gt; &lt;?php } else { ?&gt; &lt;li&gt;Unknown&lt;/li&gt; &lt;?php } ?&gt; &lt;?php } ?&gt; &lt;/ul&gt; </code></pre> <p>Can anyone point me in the right direction?</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 273872, "author": "danbrellis", "author_id": 34540, "author_profile": "https://wordpress.stackexchange.com/users/34540", "pm_score": 1, "selected": false, "text": "<p>Two options come to mind. Which one will depend on how different your content is for logged in/not logged ...
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273878", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I created some code to return attachment categories, that looks like: ``` <?php // Attachment Categories $categories = get_the_category($attachment->ID); if ($categories) { ?> <ul> <?php foreach ($categories as $category) { ?> <?php if ($category->name !== 'Slides') if ($category->name !== 'Uncategorized') { ?> <li><?php echo $category->name; ?></li> <?php } ?> <?php } ?> </ul> <?php } ?> ``` I am trying to add an `else`, but for some reason the else doesn't work with the two `if` statements...if I remove one `if` statement, the `else` works. The code with the `else` looks like: ``` <ul> <?php foreach ($categories as $category) { ?> <?php if ($category->name !== 'Slides') if ($category->name !== 'Uncategorized') { ?> <li><?php echo $category->name; ?></li> <?php } else { ?> <li>Unknown</li> <?php } ?> <?php } ?> </ul> ``` Can anyone point me in the right direction? Thanks, Josh
To use a different page's content on the homepage based on a logged-in user's role you can do this: In your functions.php file add this code: ``` function wpse_273872_pre_get_posts( $query ) { if ( $query->is_main_query() && is_user_logged_in() ) { //work-around for using is_front_page() in pre_get_posts //known bug in WP tracked by https://core.trac.wordpress.org/ticket/21790 $front_page_id = get_option('page_on_front'); $current_page_id = $query->get('page_id'); $is_static_front_page = 'page' == get_option('show_on_front'); if ($is_static_front_page && $front_page_id == $current_page_id) { $current_user = wp_get_current_user(); $user = new WP_User($current_user->ID); if (in_array('cs_candidate', $user->roles)) { //assuming the role name is cs_candidate $query->set('page_id', [page-id-for-candidate-homepage]); } elseif (in_array('cs_employer', $user->roles)) { //assuming the role name is cs_employer $query->set('page_id', [page-id-for-employer-homepage]); } } } } add_action( 'pre_get_posts', 'wpse_273872_pre_get_posts' ); ``` What this does is: 1. Filters the wp\_query args if a user is logged in, you're on the homepage and it's the main query 2. If the user has the role 'candidate', set the post id (p) to the ID of the page you created and change the post\_type to 'page' 3. Similarily, if the user has a role employer, use the ID for that page. Thanks for helping clarify all your points.
273,907
<p>I would like to write a little script that does a check whenever an order is created in WooCommerce (right after checkout) and then conditionally changes the Shipping Address of the customer.</p> <p>I think I need a filter hook that 'fires' as soon as an order is created. I tried several things in the <a href="https://docs.woocommerce.com/wc-apidocs/hook-docs.html" rel="noreferrer">WooCommerce Hook reference guide</a>, like: 'woocommerce_create_order', but without success. I also contacted WooCommerce support, but no solution. I also checked out: <a href="https://wordpress.stackexchange.com/questions/212400/woocommerce-hook-after-creating-order">Woocommerce hook after order (on Stackexchange)</a>, however I would need a filter hook that fires before order create (not after).</p> <p>What I would like to accomplish is something like:</p> <pre><code>function alter_shipping ($order) { if ($something == $condition) { $order-&gt;shipping_address = "..."; //(simplified) } return $order; } add_filter( 'woocommerce_create_order', 'alter_shipping', 10, 1 ); </code></pre> <p>This filter 'woocommerce_create_order' in above example doesn't pass any variables to be manipulated.</p> <p>I need to conditionally manipulate the shipping address in a WooCommerce order as it gets created. Does anyone know a suitable filter hook for this? Or another way?</p>
[ { "answer_id": 309707, "author": "Madebymartin", "author_id": 31520, "author_profile": "https://wordpress.stackexchange.com/users/31520", "pm_score": 4, "selected": true, "text": "<p>Stumbled on this looking for the same thing which I've now figured out (Woocommerce 3.x)...</p>\n\n<pre><...
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273907", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/86827/" ]
I would like to write a little script that does a check whenever an order is created in WooCommerce (right after checkout) and then conditionally changes the Shipping Address of the customer. I think I need a filter hook that 'fires' as soon as an order is created. I tried several things in the [WooCommerce Hook reference guide](https://docs.woocommerce.com/wc-apidocs/hook-docs.html), like: 'woocommerce\_create\_order', but without success. I also contacted WooCommerce support, but no solution. I also checked out: [Woocommerce hook after order (on Stackexchange)](https://wordpress.stackexchange.com/questions/212400/woocommerce-hook-after-creating-order), however I would need a filter hook that fires before order create (not after). What I would like to accomplish is something like: ``` function alter_shipping ($order) { if ($something == $condition) { $order->shipping_address = "..."; //(simplified) } return $order; } add_filter( 'woocommerce_create_order', 'alter_shipping', 10, 1 ); ``` This filter 'woocommerce\_create\_order' in above example doesn't pass any variables to be manipulated. I need to conditionally manipulate the shipping address in a WooCommerce order as it gets created. Does anyone know a suitable filter hook for this? Or another way?
Stumbled on this looking for the same thing which I've now figured out (Woocommerce 3.x)... ``` add_filter( 'woocommerce_checkout_create_order', 'mbm_alter_shipping', 10, 1 ); function mbm_alter_shipping ($order) { if ($something == $condition) { $address = array( 'first_name' => 'Martin', 'last_name' => 'Stevens', 'company' => 'MBM Studio', 'email' => 'test@test.com', 'phone' => '777-777-777-777', 'address_1' => '99 Arcadia Avenue', 'address_2' => '', 'city' => 'London', 'state' => '', 'postcode' => '12345', 'country' => 'UK' ); $order->set_address( $address, 'shipping' ); } return $order; } ```
273,910
<p>I have followed the solution given <a href="https://wordpress.stackexchange.com/questions/58932/how-do-i-remove-a-pre-existing-customizer-setting">here</a> by Krupal Patel.</p> <pre><code>add_action( "customize_register", "ruth_sherman_theme_customize_register" ); function ruth_sherman_theme_customize_register( $wp_customize ) { //============================================================= // Remove header image and widgets option from theme customizer //============================================================= $wp_customize-&gt;remove_control( "header_image" ); $wp_customize-&gt;remove_panel( "widgets" ); //============================================================= // Remove Colors, Background image, and Static front page // option from theme customizer //============================================================= $wp_customize-&gt;remove_section( "colors" ); $wp_customize-&gt;remove_section( "background_image" ); $wp_customize-&gt;remove_section( "static_front_page" ); } </code></pre> <p>But I am unable to remove "Theme Options", "Menus" and "Header Media". Any help?</p> <p>I am working on Twenty Seventeen.</p>
[ { "answer_id": 273921, "author": "Weston Ruter", "author_id": 8521, "author_profile": "https://wordpress.stackexchange.com/users/8521", "pm_score": 2, "selected": false, "text": "<p>The first thing to try is to increase the priority of your <code>customize_register</code> action from the...
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273910", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/4612/" ]
I have followed the solution given [here](https://wordpress.stackexchange.com/questions/58932/how-do-i-remove-a-pre-existing-customizer-setting) by Krupal Patel. ``` add_action( "customize_register", "ruth_sherman_theme_customize_register" ); function ruth_sherman_theme_customize_register( $wp_customize ) { //============================================================= // Remove header image and widgets option from theme customizer //============================================================= $wp_customize->remove_control( "header_image" ); $wp_customize->remove_panel( "widgets" ); //============================================================= // Remove Colors, Background image, and Static front page // option from theme customizer //============================================================= $wp_customize->remove_section( "colors" ); $wp_customize->remove_section( "background_image" ); $wp_customize->remove_section( "static_front_page" ); } ``` But I am unable to remove "Theme Options", "Menus" and "Header Media". Any help? I am working on Twenty Seventeen.
The first thing to try is to increase the priority of your `customize_register` action from the default of `10` to something like `100`. The reason for this is other components add their sections and controls in the same action and some after `10`, so the things you are trying to remove may simply not have been added yet. The second thing to note is that Widgets and Menus are a special case and they should not be disabled in this way. Instead, there is a dedicated filter you use to prevent them from getting loaded: ``` add_filter( 'customize_loaded_components', '__return_empty_array' ); ``` For more see the [hook docs](https://developer.wordpress.org/reference/hooks/customize_loaded_components/). See also my post on how to [reset the Customizer to a blank slate](https://make.xwp.co/2016/09/11/resetting-the-customizer-to-a-blank-slate/).
273,920
<p>I am trying to make one specific page on my wordpress installation to have a different text on the "Upload" button.</p> <p>So i tried:</p> <pre><code>function change_settingspage_publish_button( $translation, $text ) { if ( '567' == get_the_ID() &amp;&amp; $text == 'Publish' ) { return 'Save Settings'; } else { return $translation; } } add_filter( 'gettext', 'change_settingspage_publish_button', 10, 2 ); </code></pre> <p>(Where '567' is the page id). but it doesn't work. any ideas?</p>
[ { "answer_id": 273929, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 0, "selected": false, "text": "<p>You can tried this code below, it works for me.</p>\n\n<pre><code>function change_publish_button( $tran...
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273920", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124115/" ]
I am trying to make one specific page on my wordpress installation to have a different text on the "Upload" button. So i tried: ``` function change_settingspage_publish_button( $translation, $text ) { if ( '567' == get_the_ID() && $text == 'Publish' ) { return 'Save Settings'; } else { return $translation; } } add_filter( 'gettext', 'change_settingspage_publish_button', 10, 2 ); ``` (Where '567' is the page id). but it doesn't work. any ideas?
I wanted to change the Publish button's text in the Block Editor and came across this question. With the answers given it wasn't changing the text. With the Gutenberg update, I realized it would have to be done with JavaScript. I found this response: [Changing text within the Block Editor](https://wordpress.stackexchange.com/questions/328121/changing-text-within-the-block-editor) Which I applied in my plugin code (you can insert this into your Themes functions.php file, too). ``` function change_publish_button_text() { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ``` Which to your specific request to target only on a post ID you can do this: ``` function change_publish_button_text() { global $post; if (get_the_ID() == '123') { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ```
273,941
<p>Trying to create a template that places a custom post UI image between the navigation bar and the title like this:</p> <p><a href="https://i.stack.imgur.com/ZuIYa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZuIYa.png" alt="Intended outcome"></a></p> <p>However, I am unable to override the header-extensions.php in my child folder to the parent</p> <p>The page is displayed through single-program.php -> get_header(); -> header-extensions.php -> ambition_headercontent_details();</p> <p>The code that is fit between the Navbar and the title:</p> <pre><code> &lt;/div&gt;&lt;!-- .container --&gt; &lt;img id="single-program-banner" src="&lt;?php the_field('banner'); ?&gt;" alt="" /&gt; &lt;/div&gt;&lt;!-- .hgroup-wrap --&gt; </code></pre> <p>Theme I'm using <a href="https://www.themehorse.com/preview/ambition/" rel="nofollow noreferrer">https://www.themehorse.com/preview/ambition/</a></p> <p>Thank you</p>
[ { "answer_id": 273929, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 0, "selected": false, "text": "<p>You can tried this code below, it works for me.</p>\n\n<pre><code>function change_publish_button( $tran...
2017/07/19
[ "https://wordpress.stackexchange.com/questions/273941", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124196/" ]
Trying to create a template that places a custom post UI image between the navigation bar and the title like this: [![Intended outcome](https://i.stack.imgur.com/ZuIYa.png)](https://i.stack.imgur.com/ZuIYa.png) However, I am unable to override the header-extensions.php in my child folder to the parent The page is displayed through single-program.php -> get\_header(); -> header-extensions.php -> ambition\_headercontent\_details(); The code that is fit between the Navbar and the title: ``` </div><!-- .container --> <img id="single-program-banner" src="<?php the_field('banner'); ?>" alt="" /> </div><!-- .hgroup-wrap --> ``` Theme I'm using <https://www.themehorse.com/preview/ambition/> Thank you
I wanted to change the Publish button's text in the Block Editor and came across this question. With the answers given it wasn't changing the text. With the Gutenberg update, I realized it would have to be done with JavaScript. I found this response: [Changing text within the Block Editor](https://wordpress.stackexchange.com/questions/328121/changing-text-within-the-block-editor) Which I applied in my plugin code (you can insert this into your Themes functions.php file, too). ``` function change_publish_button_text() { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ``` Which to your specific request to target only on a post ID you can do this: ``` function change_publish_button_text() { global $post; if (get_the_ID() == '123') { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ```
273,958
<p>I'm working on a site that uses two different pages to filter lists of posts associated with the same custom post type ("media"), and both pages have their own templates-- a more general page named <code>page-media.php</code> and one that's more narrowly focused via taxonomy, <code>page-music-library.php</code>. While both of these pages filter lists of posts of the "media" custom post type, I would like each to render the posts in a different <code>single-</code> view when the post titles are clicked. For the main <code>page-media.php</code> template, I created a <code>single-media.php</code> template for single post views associated with that page. However, I'm not quite sure how to define an alternate <code>single-</code> view associated with the <code>page-music-library.php</code> template?</p> <p>I'm seeing from <a href="https://wordpress.stackexchange.com/questions/254845/multiple-single-post-templates">this post</a> and elsewhere that as of WP 4.7, "Post Type Templates" can offer more flexibility in this way, but I'm not clear on whether that feature would apply to my situation. Thanks for any insight here, and please let me know if my objective is unclear in any way.</p>
[ { "answer_id": 273929, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 0, "selected": false, "text": "<p>You can tried this code below, it works for me.</p>\n\n<pre><code>function change_publish_button( $tran...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/273958", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89753/" ]
I'm working on a site that uses two different pages to filter lists of posts associated with the same custom post type ("media"), and both pages have their own templates-- a more general page named `page-media.php` and one that's more narrowly focused via taxonomy, `page-music-library.php`. While both of these pages filter lists of posts of the "media" custom post type, I would like each to render the posts in a different `single-` view when the post titles are clicked. For the main `page-media.php` template, I created a `single-media.php` template for single post views associated with that page. However, I'm not quite sure how to define an alternate `single-` view associated with the `page-music-library.php` template? I'm seeing from [this post](https://wordpress.stackexchange.com/questions/254845/multiple-single-post-templates) and elsewhere that as of WP 4.7, "Post Type Templates" can offer more flexibility in this way, but I'm not clear on whether that feature would apply to my situation. Thanks for any insight here, and please let me know if my objective is unclear in any way.
I wanted to change the Publish button's text in the Block Editor and came across this question. With the answers given it wasn't changing the text. With the Gutenberg update, I realized it would have to be done with JavaScript. I found this response: [Changing text within the Block Editor](https://wordpress.stackexchange.com/questions/328121/changing-text-within-the-block-editor) Which I applied in my plugin code (you can insert this into your Themes functions.php file, too). ``` function change_publish_button_text() { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ``` Which to your specific request to target only on a post ID you can do this: ``` function change_publish_button_text() { global $post; if (get_the_ID() == '123') { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ```
273,977
<p>I'm new to wordpress, and I want to edit the <strong>homepage</strong> of a theme. I just could not find out which file should I be editing with. I've tried to remove <em>page.php</em>, <em>index.php</em>, <em>single.php</em> under /wp-content/themes/mytheme, but my site is still working after I removed all these files, so which file is the theme actually using as the homepage?</p> <p>I'm using wordpress 4.8, wooCommerce 3.1</p> <p>I'm using <strong>Rosa</strong> theme, and the files listed under the theme root are these, index.php, page.php, single.php, sidebar.php, functions.php, footer.php, comments.php header.php</p>
[ { "answer_id": 273929, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 0, "selected": false, "text": "<p>You can tried this code below, it works for me.</p>\n\n<pre><code>function change_publish_button( $tran...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/273977", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113712/" ]
I'm new to wordpress, and I want to edit the **homepage** of a theme. I just could not find out which file should I be editing with. I've tried to remove *page.php*, *index.php*, *single.php* under /wp-content/themes/mytheme, but my site is still working after I removed all these files, so which file is the theme actually using as the homepage? I'm using wordpress 4.8, wooCommerce 3.1 I'm using **Rosa** theme, and the files listed under the theme root are these, index.php, page.php, single.php, sidebar.php, functions.php, footer.php, comments.php header.php
I wanted to change the Publish button's text in the Block Editor and came across this question. With the answers given it wasn't changing the text. With the Gutenberg update, I realized it would have to be done with JavaScript. I found this response: [Changing text within the Block Editor](https://wordpress.stackexchange.com/questions/328121/changing-text-within-the-block-editor) Which I applied in my plugin code (you can insert this into your Themes functions.php file, too). ``` function change_publish_button_text() { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ``` Which to your specific request to target only on a post ID you can do this: ``` function change_publish_button_text() { global $post; if (get_the_ID() == '123') { // Make sure the `wp-i18n` has been "done". if ( wp_script_is( 'wp-i18n' ) ) : ?> <script> wp.i18n.setLocaleData({'Publish': ['Custom Publish Text']}); </script> <script> wp.i18n.setLocaleData({'Publish…': ['Custom Publish Text']}); </script> <?php endif; } } add_action( 'admin_print_footer_scripts', 'change_publish_button_text', 11 ); ```
273,986
<p>I'm having a tough time including jquery-ui scripts and styles in my plugin. It seems that my <code>wp_enqueue_script</code> calls are simply ignored.</p> <p>There are already many questions similar to this one, but all answers I've found so far boil down to call <code>wp_enqueue_script</code> inside the <code>wp_enqueue_scripts</code> action hook, which I'm already doing.</p> <p>In the constructor of my class I call:</p> <pre><code>add_action( 'wp_enqueue_scripts', array($this, 'enqueue_scripts') ); </code></pre> <p>and then, below:</p> <pre><code>public function enqueue_scripts() { wp_enqueue_script( 'jquery-ui-core', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-widget', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-mouse', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-accordion', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-autocomplete', false, array('jquery')); wp_enqueue_script( 'jquery-ui-slider', false, array('jquery')); </code></pre> <p>I've checked that the code actually gets executed each page load. However the pages lack the <code>&lt;link&gt;</code> tags for the jquery-ui library. I've already tried with and without the <code>jquery</code> dependency explicitly specified in the third argument of the <code>wp_enqueue_script</code> calls.</p> <p>I've also tried with a plain WP 4.8 installation with no plugins installed other than mine, and with the default twenty seventeen theme only. No dice.</p> <p>What's wrong with my code?</p>
[ { "answer_id": 273993, "author": "umesh.nevase", "author_id": 9279, "author_profile": "https://wordpress.stackexchange.com/users/9279", "pm_score": 1, "selected": false, "text": "<p>I've modified your script. try with this, it is working.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/273986", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84622/" ]
I'm having a tough time including jquery-ui scripts and styles in my plugin. It seems that my `wp_enqueue_script` calls are simply ignored. There are already many questions similar to this one, but all answers I've found so far boil down to call `wp_enqueue_script` inside the `wp_enqueue_scripts` action hook, which I'm already doing. In the constructor of my class I call: ``` add_action( 'wp_enqueue_scripts', array($this, 'enqueue_scripts') ); ``` and then, below: ``` public function enqueue_scripts() { wp_enqueue_script( 'jquery-ui-core', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-widget', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-mouse', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-accordion', false, array('jquery') ); wp_enqueue_script( 'jquery-ui-autocomplete', false, array('jquery')); wp_enqueue_script( 'jquery-ui-slider', false, array('jquery')); ``` I've checked that the code actually gets executed each page load. However the pages lack the `<link>` tags for the jquery-ui library. I've already tried with and without the `jquery` dependency explicitly specified in the third argument of the `wp_enqueue_script` calls. I've also tried with a plain WP 4.8 installation with no plugins installed other than mine, and with the default twenty seventeen theme only. No dice. What's wrong with my code?
First of all, WordPress registers jQuery UI via [`wp_default_scripts()`](https://stackoverflow.com/questions/8849684/wordpress-jquery-ui-css-files). Dependencies are already set, so you only need to enqueue the script you really need (and not the core). Since you're not changing version number or anything, it is ok to only use the handle. ``` // no need to enqueue -core, because dependancies are set wp_enqueue_script( 'jquery-ui-widget' ); wp_enqueue_script( 'jquery-ui-mouse' ); wp_enqueue_script( 'jquery-ui-accordion' ); wp_enqueue_script( 'jquery-ui-autocomplete' ); wp_enqueue_script( 'jquery-ui-slider' ); ``` As for the stylesheets: **WordPress does not register jQuery UI styles by default!** In the comments, [butlerblog pointed out](https://wordpress.stackexchange.com/questions/273986/correct-way-to-enqueue-jquery-ui/273996#comment523572_273996) that according to the [Plugin Guidelines](https://developer.wordpress.org/plugins/wordpress-org/detailed-plugin-guidelines/#8-plugins-may-not-send-executable-code-via-third-party-systems) > > Executing outside code within a plugin when not acting as a service is not allowed, for example: > > > * Calling third party CDNs for reasons other than font inclusions; all non-service related JavaScript and CSS must be included locally > > > This means loading the styles via CDN is not permitted and should always be done locally. You can do so by using `wp_enqueue_style()`.
274,016
<p>I would like to add content to the end of <a href="https://www.horizonhomes-samui.com/contact/" rel="nofollow noreferrer">this page</a> (below the form), immediately before the footer. Can I do this with a custom function, via a hook? Adding the content to the WordPress editor does not insert it at the bottom of the page as desired.</p> <p>I've tried two different custom functions, but they each placed the content in an undesired location (<a href="https://imgur.com/66runIU" rel="nofollow noreferrer">illustration</a>):</p> <p>-- I tried using the <code>wp_footer()</code> hook, but that placed the content at the end of my footer.</p> <p>-- I tried appending content using <code>the_content()</code> hook, with the code below, but that did not place the content where I wanted.</p> <pre><code>function yourprefix_add_to_content( $content ) { $content .= 'Your new content here'; return $content; } add_filter( 'the_content', 'yourprefix_add_to_content' ); </code></pre> <p>I <em>can</em> accomplish this by directly editing template, but I would rather not do that.</p>
[ { "answer_id": 274024, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>Unless that template that you don't want to edit has a <code>do_action()</code> function where you want ...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274016", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51204/" ]
I would like to add content to the end of [this page](https://www.horizonhomes-samui.com/contact/) (below the form), immediately before the footer. Can I do this with a custom function, via a hook? Adding the content to the WordPress editor does not insert it at the bottom of the page as desired. I've tried two different custom functions, but they each placed the content in an undesired location ([illustration](https://imgur.com/66runIU)): -- I tried using the `wp_footer()` hook, but that placed the content at the end of my footer. -- I tried appending content using `the_content()` hook, with the code below, but that did not place the content where I wanted. ``` function yourprefix_add_to_content( $content ) { $content .= 'Your new content here'; return $content; } add_filter( 'the_content', 'yourprefix_add_to_content' ); ``` I *can* accomplish this by directly editing template, but I would rather not do that.
Unless that template that you don't want to edit has a `do_action()` function where you want to add the content, then no, you can't.
274,017
<p>I'm a WordPress beginner and I'm working on a travel directory that user can register and have a front end control panel and have a front end submission form where user can add property description and of course images . </p> <p>I have a multi site installation but upload settings do not work for front end(max upload file size and file type). I suppose I can use a filter but I could not find something that works for front end... tried several plugins , all work in back end. </p> <p>Actually I need a step by step help or on line guide I could not find yet.</p> <p>Thanks!</p>
[ { "answer_id": 274019, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 0, "selected": false, "text": "<p>You have some ways to do that:</p>\n\n<p>In your <strong>functions.php</strong> or <strong...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274017", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123557/" ]
I'm a WordPress beginner and I'm working on a travel directory that user can register and have a front end control panel and have a front end submission form where user can add property description and of course images . I have a multi site installation but upload settings do not work for front end(max upload file size and file type). I suppose I can use a filter but I could not find something that works for front end... tried several plugins , all work in back end. Actually I need a step by step help or on line guide I could not find yet. Thanks!
You have some ways to do that: In your **functions.php** or **wp-config.php** ``` @ini_set( 'upload_max_size' , '15M' ); @ini_set( 'post_max_size', '15M'); @ini_set( 'max_execution_time', '300' ); ``` In your **.htaccess** (if you use apache2) ``` php_value upload_max_filesize 15M php_value post_max_size 15M php_value max_execution_time 300 php_value max_input_time 300 ``` If you use **nginx** ``` http { client_max_body_size 15m; } ``` In your **php.ini** ``` upload_max_filesize = 15M post_max_size = 15M max_execution_time = 300 ``` They all work, so you can choose what best suits you, the size is set in MB so all the examples above will set the max upload to **15MB**.
274,034
<p>I have setup a small website using LAMP (Raspbian) and Wordpress.<br> No domain name will be registered for the website.<br> For the moment I am accessing the site from inside the local network.<br> To access the site I just hit the IP address of the server (internal).<br> I want to access the site from outside the local network via the public IP.<br> The public IP is static and a Firewall is configured to translate the internal IP/default port(80) to the public static IP/(random port) and vice versa. Internal IP is static also and the RPi is directly connected to the FW via cable.</p> <p>If I send a request from an external IP the page never loads and inside my admin panel(via WP Statistics plugin) I can see the request.</p> <p>I would like to note that I have modified the <code>wp-config.php</code> and specifically these lines: </p> <pre><code>define('WP_HOME','http://internalIP/'); define('WP_SITEURL','http://internalIP/'); </code></pre> <p>What changes do I need to make so that the site will respond to the external requests? </p> <p>Is there anything I should check in my Wordpress/Apache/mySql/Linux configuration? </p> <p>Please let me know if any configuration info would be useful.</p>
[ { "answer_id": 274066, "author": "user42826", "author_id": 42826, "author_profile": "https://wordpress.stackexchange.com/users/42826", "pm_score": 2, "selected": true, "text": "<p>When installing WP onto an IP address (or hostname), WP will only respond to requests on that IP address. A...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274034", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63180/" ]
I have setup a small website using LAMP (Raspbian) and Wordpress. No domain name will be registered for the website. For the moment I am accessing the site from inside the local network. To access the site I just hit the IP address of the server (internal). I want to access the site from outside the local network via the public IP. The public IP is static and a Firewall is configured to translate the internal IP/default port(80) to the public static IP/(random port) and vice versa. Internal IP is static also and the RPi is directly connected to the FW via cable. If I send a request from an external IP the page never loads and inside my admin panel(via WP Statistics plugin) I can see the request. I would like to note that I have modified the `wp-config.php` and specifically these lines: ``` define('WP_HOME','http://internalIP/'); define('WP_SITEURL','http://internalIP/'); ``` What changes do I need to make so that the site will respond to the external requests? Is there anything I should check in my Wordpress/Apache/mySql/Linux configuration? Please let me know if any configuration info would be useful.
When installing WP onto an IP address (or hostname), WP will only respond to requests on that IP address. Any request from another IP address even if it resolves to the same server, will result in a redirect to a WP error page. In this situation, I would do this: 1. Install WP on the public IP address. This will work if you can route to the public IP address internally. 2. f you cannot route to the public IP address internally then I suggest installing on a hostname. You need to configure your DNS so that internally it will resolve to the internal IP address; and externally it will resolve to the public IP address.
274,038
<p>I am using <em>pre_get_posts hook</em> in order to filter posts by custom terms. All working fine, but if i want to filter posts by 2 custom terms, the query only filters by the last term given. See my code below. I hook this into <em>pre_get_posts</em> but when both if statements are TRUE, only the last $query->set is done, meaning it won't filter the posts twice. Is there any way to accomplish this? Thanks</p> <pre><code>//For searching if( $query-&gt;is_main_query() &amp;&amp; isset( $_GET[ 'ls' ] ) ) { $rt_term_id = $_GET['listing_soort']; $rt_term_id_land = $_GET['listing_land']; // IF our soort vakantie is set and not empty - include it in the query if( isset( $rt_term_id ) &amp;&amp; ! empty( $rt_term_id ) ) { $query-&gt;set( 'tax_query', array( array( 'taxonomy' =&gt; 'vakantiesoorten_listing', 'field' =&gt; 'id', 'terms' =&gt; array($rt_term_id[0]), ) ) ); } // IF our land vakantie is set and not empty - include it in the query if( empty($_GET['location_geo_data']) &amp;&amp; isset( $rt_term_id_land ) &amp;&amp; ! empty( $rt_term_id_land ) ) { $query-&gt;set( 'tax_query', array( array( 'taxonomy' =&gt; 'landen_listing', 'field' =&gt; 'id', 'terms' =&gt; array($rt_term_id_land[0]), ) ) ); } } </code></pre>
[ { "answer_id": 274040, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You can do this, you just need to get the original value of the tax query, add the additional query, th...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274038", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124244/" ]
I am using *pre\_get\_posts hook* in order to filter posts by custom terms. All working fine, but if i want to filter posts by 2 custom terms, the query only filters by the last term given. See my code below. I hook this into *pre\_get\_posts* but when both if statements are TRUE, only the last $query->set is done, meaning it won't filter the posts twice. Is there any way to accomplish this? Thanks ``` //For searching if( $query->is_main_query() && isset( $_GET[ 'ls' ] ) ) { $rt_term_id = $_GET['listing_soort']; $rt_term_id_land = $_GET['listing_land']; // IF our soort vakantie is set and not empty - include it in the query if( isset( $rt_term_id ) && ! empty( $rt_term_id ) ) { $query->set( 'tax_query', array( array( 'taxonomy' => 'vakantiesoorten_listing', 'field' => 'id', 'terms' => array($rt_term_id[0]), ) ) ); } // IF our land vakantie is set and not empty - include it in the query if( empty($_GET['location_geo_data']) && isset( $rt_term_id_land ) && ! empty( $rt_term_id_land ) ) { $query->set( 'tax_query', array( array( 'taxonomy' => 'landen_listing', 'field' => 'id', 'terms' => array($rt_term_id_land[0]), ) ) ); } } ```
Think of this pseudo code ``` if sky == blue set a = 5 if grass == green set a = 7 ``` What value will `a` have? Not 12. This is the exact same situation. You are setting a specific parameter to a specific value. In the second call, you are overwriting your previous value. To avoid this, you can build the value (here the array) beforehand, and call `->set()` only once. ``` $tax_query = array(); if( isset( $rt_term_id ) && ! empty( $rt_term_id ) ) { $tax_query[] = array( 'taxonomy' => 'vakantiesoorten_listing', 'field' => 'id', 'terms' => array($rt_term_id[0]), ); } if( empty($_GET['location_geo_data']) && isset( $rt_term_id_land ) && ! empty( $rt_term_id_land ) ) { $tax_query[] = array( 'taxonomy' => 'landen_listing', 'field' => 'id', 'terms' => array($rt_term_id_land[0]), ); } $query->set( 'tax_query', $tax_query ); ```
274,039
<p>I have mt theme folder in my computer, where I did all the updates. Now I want to upload the new version of my theme with the changes I did. My question here: Do I just upload the theme folder via FTP and overwrite the existing one? Will this damage or change my posts or it will just update the theme design? I did this last night, but I'm afraid it changes everything...</p>
[ { "answer_id": 274040, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>You can do this, you just need to get the original value of the tax query, add the additional query, th...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274039", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114684/" ]
I have mt theme folder in my computer, where I did all the updates. Now I want to upload the new version of my theme with the changes I did. My question here: Do I just upload the theme folder via FTP and overwrite the existing one? Will this damage or change my posts or it will just update the theme design? I did this last night, but I'm afraid it changes everything...
Think of this pseudo code ``` if sky == blue set a = 5 if grass == green set a = 7 ``` What value will `a` have? Not 12. This is the exact same situation. You are setting a specific parameter to a specific value. In the second call, you are overwriting your previous value. To avoid this, you can build the value (here the array) beforehand, and call `->set()` only once. ``` $tax_query = array(); if( isset( $rt_term_id ) && ! empty( $rt_term_id ) ) { $tax_query[] = array( 'taxonomy' => 'vakantiesoorten_listing', 'field' => 'id', 'terms' => array($rt_term_id[0]), ); } if( empty($_GET['location_geo_data']) && isset( $rt_term_id_land ) && ! empty( $rt_term_id_land ) ) { $tax_query[] = array( 'taxonomy' => 'landen_listing', 'field' => 'id', 'terms' => array($rt_term_id_land[0]), ); } $query->set( 'tax_query', $tax_query ); ```
274,042
<p>i want to display a div on every single page, but not on the frontpage. For that i used the following code in the functions.php</p> <pre><code> if (! is_front_page()) : '&lt;div class="button-kontakt"&gt; &lt;a href="/kontakt"&gt;&lt;p&gt;ANFRAGE&lt;/p&gt;&lt;/a&gt;&lt;/div&gt;'; endif; </code></pre> <p>But my code is not working? The div is not shown. Somebody could help me with this?</p> <p>best regards</p> <p>Tom</p>
[ { "answer_id": 274045, "author": "James", "author_id": 122472, "author_profile": "https://wordpress.stackexchange.com/users/122472", "pm_score": 2, "selected": true, "text": "<p>You need to tell the PHP to echo the div. </p>\n\n<p><code>if (! is_front_page()) : \n echo '&lt;div class=\...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274042", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82174/" ]
i want to display a div on every single page, but not on the frontpage. For that i used the following code in the functions.php ``` if (! is_front_page()) : '<div class="button-kontakt"> <a href="/kontakt"><p>ANFRAGE</p></a></div>'; endif; ``` But my code is not working? The div is not shown. Somebody could help me with this? best regards Tom
You need to tell the PHP to echo the div. `if (! is_front_page()) : echo '<div class="button-kontakt"> <a href="/kontakt"><p>ANFRAGE</p></a></div>'; endif;` Unless you just want it on the top of the page, you need to add that code to a template file, not the functions file. If it is something that appears at the bottom of every page except the homepage, putting it in footer.php may be applicable. Also, have you set the page you don't want to see it on as the front page via the option in the Appearance->Customise menu?
274,049
<p>I'm using gulp &amp; browserSync for server in WP development: </p> <pre><code>gulp.task('browser-sync', function () { browserSync.init({ proxy: projectURL }); }); </code></pre> <p>WordPress runs on <code>localhost:3000/mysite</code></p> <p>There is also a watch task that detects changes in php and reloads browser.</p> <p>For some reason though WP customizer doesn't load site in iframe with the following error: </p> <pre><code>Refused to display 'http://localhost:3000/mysite/2012/01/07/template-sticky/?customize_changese…10a90359901&amp;customize_theme=mysite&amp;customize_messenger_channel=preview-0' in a frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors http://localhost". </code></pre> <p>It works fine <code>http://localhost/mysite</code> without the port though, but won't reload automatically. </p> <p>Is there a way to fix this somehow? </p>
[ { "answer_id": 290771, "author": "tpaksu", "author_id": 14452, "author_profile": "https://wordpress.stackexchange.com/users/14452", "pm_score": 1, "selected": false, "text": "<p>Maybe it may be late, but I recently have found a solution with a filter:</p>\n\n<pre><code>function theme_set...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274049", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121208/" ]
I'm using gulp & browserSync for server in WP development: ``` gulp.task('browser-sync', function () { browserSync.init({ proxy: projectURL }); }); ``` WordPress runs on `localhost:3000/mysite` There is also a watch task that detects changes in php and reloads browser. For some reason though WP customizer doesn't load site in iframe with the following error: ``` Refused to display 'http://localhost:3000/mysite/2012/01/07/template-sticky/?customize_changese…10a90359901&customize_theme=mysite&customize_messenger_channel=preview-0' in a frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors http://localhost". ``` It works fine `http://localhost/mysite` without the port though, but won't reload automatically. Is there a way to fix this somehow?
Found a work around by adding ' localhost:3000' to the 'Content-Security-Policy' header: ``` function edit_customizer_headers () { function edit_csp_header ($headers) { $headers['Content-Security-Policy'] .= ' localhost:3000'; return $headers; } add_filter('wp_headers', 'edit_csp_header'); } add_action('customize_preview_init', 'edit_customizer_headers'); ```
274,056
<p><a href="https://i.stack.imgur.com/a91zO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a91zO.jpg" alt="SearchResultsPage"></a></p> <p>I have designed and developed a responsive Wordpress site that is almost ready for launch for a client who is an actor and producer. I have been stuck on my requirements for the search results page for three days.</p> <p>My EXCERPT is far too long and includes repeated text from the Home page no matter what the search is for. Under the white links to the posts and pages for the search results, I want an excerpt of no more than 30 words which includes the search keyword (in this case the search keyword being “Ginsberg”) highlighted. So, a snippet of about 30 words, including the search term highlighted. That’s what I can’t get. When I have that, I have the search page I want. </p> <p>I have spent hours Googling and searching this on Stack Exchange and Stack Overflow, as well as attempts at finding the PHP logic required myself and failing. So if there is a solution to this already here, it’s well hidden!!</p> <p>WHAT I DO HAVE AND WHAT I’M HAPPY WITH IS: Say I do a search for the Beat Poet “Ginsberg” (screen shot attached). I get a main heading saying “2 results found for “Ginsberg”. Under that a smaller heading saying “Your ‘Ginsberg search results can be found at”” then below that I get a nicely styled list of two links to the two relevant pages. I want all that. That’s great. </p> <p>MY SEARCH FORM:</p> <pre><code>&lt;div class="search-cont"&gt; &lt;form class="searchinput" method="get" action="&lt;?php echo home_url(); ?&gt;" role="search"&gt; &lt;input type="search" class="searchinput" placeholder="&lt;?php echo esc_attr_x( 'Click icon or hit enter to search..', 'placeholder' ) ?&gt;" value="&lt;?php get_search_query() ?&gt;" name="s" title="&lt;?php echo esc_attr_x( 'Search for:', 'label' ) ?&gt;" /&gt; &lt;button type="submit" role="button" class="search-btn"/&gt;&lt;i class="fa fa-search" aria-hidden="true"&gt;&lt;/i&gt;&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>=--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- MY SEARCH PAGE:</p> <pre><code>&lt;div class="searchresultsbox"&gt; &lt;?php global $wp_query;?&gt; &lt;h2&gt; &lt;?php echo $wp_query-&gt;found_posts; ?&gt;&lt;?php _e( ' results found for', 'locale' ); ?&gt;: "&lt;?php the_search_query(); ?&gt;"&lt;/h2&gt; &lt;?php if ( have_posts() ) { ?&gt; &lt;h3&gt;&lt;?php printf( __( 'Your "%s" search results can be found at:', 'ptpisblogging' ), get_search_query() ); ?&gt;&lt;/h3&gt; &lt;?php while ( have_posts() ) { the_post(); ?&gt; &lt;h3&gt;&lt;a href="&lt;?php echo get_permalink(); ?&gt;"&gt; &lt;?php the_title(); ?&gt; &lt;/a&gt;&lt;/h3&gt; &lt;?php //echo substr(get_the_excerpt(), 0, 2); ?&gt; &lt;div class="h-readmore"&gt; &lt;a href="&lt;?php //the_permalink(); ?&gt;"&gt;&lt;/a&gt;&lt;/div&gt; &lt;?php $args=array('s'=&gt;'test','order'=&gt; 'DESC', 'posts_per_page'=&gt;get_option('posts_per_page')); $query=new WP_Query($args); if( $query-&gt;have_posts()): while( $query-&gt;have_posts()): $query-&gt;the_post(); { echo $post-&gt;post_title; echo $post-&gt;post_content; } endwhile; else: endif; ?&gt; &lt;?php } ?&gt; &lt;?php paginate_links(); ?&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;param name="" value=""&gt; &lt;/div&gt;&lt;!-- /searchresultsbox --&gt; &lt;/div&gt;&lt;!-- /collcelltwo --&gt; &lt;/div&gt;&lt;!-- /tb-one-row --&gt; &lt;/div&gt;&lt;!-- /tb-one --&gt; </code></pre> <p>=--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- =--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- IN 'functions.php'</p> <pre><code>add_action( 'pre_get_posts', function( $query ) { // Check that it is the query we want to change: front-end search query if( $query-&gt;is_main_query() &amp;&amp; ! is_admin() &amp;&amp; $query-&gt;is_search() ) { // Change the query parameters $query-&gt;set( 'posts_per_page', 4 ); } } ); </code></pre> <p>I am extremely grateful for your input. Thank you!! Keith</p>
[ { "answer_id": 274065, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>Use str_replace to replace all occurances of the word to highlight with a around the word. Something ...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274056", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124257/" ]
[![SearchResultsPage](https://i.stack.imgur.com/a91zO.jpg)](https://i.stack.imgur.com/a91zO.jpg) I have designed and developed a responsive Wordpress site that is almost ready for launch for a client who is an actor and producer. I have been stuck on my requirements for the search results page for three days. My EXCERPT is far too long and includes repeated text from the Home page no matter what the search is for. Under the white links to the posts and pages for the search results, I want an excerpt of no more than 30 words which includes the search keyword (in this case the search keyword being “Ginsberg”) highlighted. So, a snippet of about 30 words, including the search term highlighted. That’s what I can’t get. When I have that, I have the search page I want. I have spent hours Googling and searching this on Stack Exchange and Stack Overflow, as well as attempts at finding the PHP logic required myself and failing. So if there is a solution to this already here, it’s well hidden!! WHAT I DO HAVE AND WHAT I’M HAPPY WITH IS: Say I do a search for the Beat Poet “Ginsberg” (screen shot attached). I get a main heading saying “2 results found for “Ginsberg”. Under that a smaller heading saying “Your ‘Ginsberg search results can be found at”” then below that I get a nicely styled list of two links to the two relevant pages. I want all that. That’s great. MY SEARCH FORM: ``` <div class="search-cont"> <form class="searchinput" method="get" action="<?php echo home_url(); ?>" role="search"> <input type="search" class="searchinput" placeholder="<?php echo esc_attr_x( 'Click icon or hit enter to search..', 'placeholder' ) ?>" value="<?php get_search_query() ?>" name="s" title="<?php echo esc_attr_x( 'Search for:', 'label' ) ?>" /> <button type="submit" role="button" class="search-btn"/><i class="fa fa-search" aria-hidden="true"></i></button> </form> </div> ``` =--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- MY SEARCH PAGE: ``` <div class="searchresultsbox"> <?php global $wp_query;?> <h2> <?php echo $wp_query->found_posts; ?><?php _e( ' results found for', 'locale' ); ?>: "<?php the_search_query(); ?>"</h2> <?php if ( have_posts() ) { ?> <h3><?php printf( __( 'Your "%s" search results can be found at:', 'ptpisblogging' ), get_search_query() ); ?></h3> <?php while ( have_posts() ) { the_post(); ?> <h3><a href="<?php echo get_permalink(); ?>"> <?php the_title(); ?> </a></h3> <?php //echo substr(get_the_excerpt(), 0, 2); ?> <div class="h-readmore"> <a href="<?php //the_permalink(); ?>"></a></div> <?php $args=array('s'=>'test','order'=> 'DESC', 'posts_per_page'=>get_option('posts_per_page')); $query=new WP_Query($args); if( $query->have_posts()): while( $query->have_posts()): $query->the_post(); { echo $post->post_title; echo $post->post_content; } endwhile; else: endif; ?> <?php } ?> <?php paginate_links(); ?> <?php } ?> </div> </div> </div> <param name="" value=""> </div><!-- /searchresultsbox --> </div><!-- /collcelltwo --> </div><!-- /tb-one-row --> </div><!-- /tb-one --> ``` =--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- =--=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-==-=-=-=-=-=-=- IN 'functions.php' ``` add_action( 'pre_get_posts', function( $query ) { // Check that it is the query we want to change: front-end search query if( $query->is_main_query() && ! is_admin() && $query->is_search() ) { // Change the query parameters $query->set( 'posts_per_page', 4 ); } } ); ``` I am extremely grateful for your input. Thank you!! Keith
This will helpful for you... Use this code at function.php ``` function wps_highlight_results($text){ if(is_search()){ $sr = get_query_var('s'); $keys = explode(" ",$sr); $text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">'.$sr.'</strong>', $text); } return $text; } add_filter('the_excerpt', 'wps_highlight_results'); ```
274,097
<p>Right now my domain <code>www.example.com</code> is setup to force HTTPS and it works. The site also correctly links everything to HTTPS. (there are no occurences of HTTP in the database anywhere).</p> <p>But if you are visiting a subpage, you can change the url to HTTP again, for example <code>http://example.com/subpage/</code> and it will not enforce HTTPS.</p> <p>I have this rule in my <code>.htaccess</code> in the root:</p> <pre><code>RewriteEngine On RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://example.com/$1 [R,L] </code></pre> <p>Any ideas what the cause of this is?</p>
[ { "answer_id": 274098, "author": "Junaid", "author_id": 66571, "author_profile": "https://wordpress.stackexchange.com/users/66571", "pm_score": 0, "selected": false, "text": "<p>Try this <code>htaccess</code> rule</p>\n\n<pre><code>RewriteCond %{HTTPS} !=on\nRewriteRule ^ https://%{HTTP_...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274097", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124277/" ]
Right now my domain `www.example.com` is setup to force HTTPS and it works. The site also correctly links everything to HTTPS. (there are no occurences of HTTP in the database anywhere). But if you are visiting a subpage, you can change the url to HTTP again, for example `http://example.com/subpage/` and it will not enforce HTTPS. I have this rule in my `.htaccess` in the root: ``` RewriteEngine On RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://example.com/$1 [R,L] ``` Any ideas what the cause of this is?
To globally redirect all your pages to HTTPS add the following lines to your `.htaccess`: ``` # Globally force SSL. RewriteCond %{HTTPS} off RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] ``` This should be placed directly after `RewriteEngine on` if you have no previous rewrites.
274,103
<p>I'm wondering how I could change the menu in the twenty twelve theme to show the submenu items on click rather than hover?</p>
[ { "answer_id": 274106, "author": "Cedon", "author_id": 80069, "author_profile": "https://wordpress.stackexchange.com/users/80069", "pm_score": -1, "selected": false, "text": "<p>You add a <code>:focus</code> pseudoclass to the same rule as <code>:hover</code>.</p>\n\n<pre><code>a:hover {...
2017/07/20
[ "https://wordpress.stackexchange.com/questions/274103", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121004/" ]
I'm wondering how I could change the menu in the twenty twelve theme to show the submenu items on click rather than hover?
Menus can be slightly confusing since there's often JS and CSS interacting with different things. Looking at the twentytwelve theme, a quick method of achieving this would be to remove the CSS that is adding :hover display of the submenus. In [style.css you would see .main-navigation ul li:hover > ul, on line 1,567](https://github.com/WordPress/WordPress/blob/master/wp-content/themes/twentytwelve/style.css#L1567). In your child theme, you could just remove that selector and keep the other two selectors and all the properties in tact. That disables the :hover, but then you also need to make decisions on the behavior of the menu, submenus, and submenu submenus etc. Do you expect the submenus with submenus to behave the same way? Are you going to disable the top level menu item that is nested underneath? Are you going to create a toggle next to the menu item and keep the link clickable on the parent? Maybe a single click opens the submenu, and doubleclick takes the user to the URL? Paired with removing the CSS from above, you could have the parent menu item simply be a custom link going to '#' and the link text whatever you want the parent item to be. Twentytwelve already includes JS in the [js/navigation.js file](https://github.com/WordPress/WordPress/blob/master/wp-content/themes/twentytwelve/js/navigation.js#L41), which is handling toggling a focus class on the element, so everything should work for you just removing that one line of CSS and changing your menu structure up. If this is for your own site or a controlled environment, then that might be all you need. If you don't want to change the menu structure, or want an alternative solution to handling that, you could easily use JS to prevent the links from being followed on click as well. This code would allow that to happen and you wouldn't have to mess around with your menu structure: ``` ( function( $ ) { $( '#menu-primary' ).find( '.menu-item-has-children > a' ).on( 'click', function( e ) { e.preventDefault(); }); } )( jQuery ); ``` If you're creating a new theme based on twentytwelve, then you should also give consideration to how others might intend to use the theme and prefer for their menus to work. You could create customizer controls to allow toggling the behavior of hover vs click and allowing parent menu items to be links etc. EDIT: **How would your JS affect users who don't use mice though?** The best way to tell is to try it out! :P 1. Keyboard navigation: In testing this solution without a mouse by using my keyboard, I am able to successfully tab through the menus, submenus, and nested submenus easily. Pressing enter did not take me to the links of items that had children, but pressing enter on the final child allows the link to be opened. This seems like it works in the way that I would expect the navigation to work from a keyboard from the op's question. It probably wouldn't be harmful to rewrite the nav with aria labels to provide a better experience for users on screen readers, and allow better handling of the navigation with arrow keys if that's a concern for your site. 2. Mobile or Touch Devices: The click event would be the last fired for a touch click simulation. The flow through events for touch would be: * touchstart * touchmove * touchend * mouseover * mousemove * mousedown * mouseup * click Twentytwelve is already [handling the mobile menus on the touchstart event in their navigation.js](https://github.com/WordPress/WordPress/blob/master/wp-content/themes/twentytwelve/js/navigation.js#L44), so calling preventDefault on click should still be fine to have it behave as well on mobile.
274,116
<p>Due to the setup of my template (and layout), I need to be able to place 4 different posts in 4 different divs.</p> <p>For example, my structure would be like this</p> <pre><code>&lt;div&gt;Post 1&lt;/div&gt; &lt;div&gt; &lt;div&gt;Post 2&lt;/div&gt; &lt;div&gt; &lt;div&gt;Post 3&lt;/div&gt; &lt;div&gt;Post 4&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>But I'm having some trouble getting this to work, I use <code>get_posts</code> to get the 4 latest posts.</p> <pre><code>$posts = get_posts(array( 'post_type' =&gt; 'post', 'post_count' =&gt; 4 )); </code></pre> <p>And then I try to display my post</p> <pre><code>&lt;?php setup_postdata($posts[0]); ?&gt; &lt;?php get_template_part( 'template-parts/post-thumbnail' ); ?&gt; &lt;?php wp_reset_postdata(); ?&gt; </code></pre> <p>In <code>template-parts/post-thumbnail.php</code> I'm trying to display the title and permalink, but it's always showing the title and link of the current page. Never of the actual post.</p>
[ { "answer_id": 274119, "author": "While1", "author_id": 111798, "author_profile": "https://wordpress.stackexchange.com/users/111798", "pm_score": 2, "selected": false, "text": "<p>Take it to your provinces</p>\n\n<pre><code>&lt;?php foreach ($posts as $post) : setup_postdata( $post ); ?&...
2017/07/21
[ "https://wordpress.stackexchange.com/questions/274116", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17561/" ]
Due to the setup of my template (and layout), I need to be able to place 4 different posts in 4 different divs. For example, my structure would be like this ``` <div>Post 1</div> <div> <div>Post 2</div> <div> <div>Post 3</div> <div>Post 4</div> </div> </div> ``` But I'm having some trouble getting this to work, I use `get_posts` to get the 4 latest posts. ``` $posts = get_posts(array( 'post_type' => 'post', 'post_count' => 4 )); ``` And then I try to display my post ``` <?php setup_postdata($posts[0]); ?> <?php get_template_part( 'template-parts/post-thumbnail' ); ?> <?php wp_reset_postdata(); ?> ``` In `template-parts/post-thumbnail.php` I'm trying to display the title and permalink, but it's always showing the title and link of the current page. Never of the actual post.
Your problem is that the variable passed to `setup_postdata()` *must* be the global `$post` variable, like this: ``` // Reference global $post variable. global $post; // Get posts. $posts = get_posts(array( 'post_type' => 'post', 'post_count' => 4 )); // Set global post variable to first post. $post = $posts[0]; // Setup post data. setup_postdata( $post ); // Output template part. get_template_part( 'template-parts/post-thumbnail' ); // Reset post data. wp_reset_postdata(); ``` Now normal template functions, like `the_post_thumbnail()` inside the template part will reference the correct post.
274,145
<p>I have a taxonomy page called <code>taxonomy-hotels.php</code> I need to get all posts related to particular <code>taxonomy-term</code>. Assume I have a term <code>5 star hotel</code> and it has 15 posts. But ony 10 returning/showing.</p> <p>Pleasa let me know how to get all posts ? Here is my current code.</p> <pre><code> &lt;?php if(have_posts()) : while(have_posts()) : the_post(); ?&gt; &lt;div class="col-lg-4 col-md-4 col-sm-4 col-xs-12"&gt; &lt;div class="item"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; endif; ?&gt; </code></pre>
[ { "answer_id": 274119, "author": "While1", "author_id": 111798, "author_profile": "https://wordpress.stackexchange.com/users/111798", "pm_score": 2, "selected": false, "text": "<p>Take it to your provinces</p>\n\n<pre><code>&lt;?php foreach ($posts as $post) : setup_postdata( $post ); ?&...
2017/07/21
[ "https://wordpress.stackexchange.com/questions/274145", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85766/" ]
I have a taxonomy page called `taxonomy-hotels.php` I need to get all posts related to particular `taxonomy-term`. Assume I have a term `5 star hotel` and it has 15 posts. But ony 10 returning/showing. Pleasa let me know how to get all posts ? Here is my current code. ``` <?php if(have_posts()) : while(have_posts()) : the_post(); ?> <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12"> <div class="item"> <a href="<?php the_permalink(); ?>"> <h2><?php the_title(); ?></h2> <?php the_post_thumbnail(); ?> </a> </div> </div> <?php endwhile; endif; ?> ```
Your problem is that the variable passed to `setup_postdata()` *must* be the global `$post` variable, like this: ``` // Reference global $post variable. global $post; // Get posts. $posts = get_posts(array( 'post_type' => 'post', 'post_count' => 4 )); // Set global post variable to first post. $post = $posts[0]; // Setup post data. setup_postdata( $post ); // Output template part. get_template_part( 'template-parts/post-thumbnail' ); // Reset post data. wp_reset_postdata(); ``` Now normal template functions, like `the_post_thumbnail()` inside the template part will reference the correct post.
274,206
<p>The following loop works great for me in getting posts with a given date with the use of the_time(...):</p> <pre><code>&lt;?php $myPost = new WP_Query( array( 'posts_per_page' =&gt; '50', 'orderby' =&gt; 'modified', 'order' =&gt; 'DESC' )); while ($myPost-&gt;have_posts()): $myPost-&gt;the_post(); ?&gt; &lt;div class="timeline-group"&gt; &lt;p class="modified-time"&gt;&lt;?php the_time('F j, Y') ?&gt;&lt;/p&gt; &lt;h5&gt;&lt;a href="&lt;?php the_permalink();?&gt;"&gt;&lt;?php the_title();?&gt;&lt;/a&gt;&lt;/h5&gt; &lt;/div&gt; &lt;?php endwhile; //Reset Post Data wp_reset_postdata(); ?&gt; </code></pre> <p>But the first 10 posts always show the same date (i.e. July 21, 2017). I want to display that date only once for these 10 posts. And if I create a new post tomorrow, then it should then show a new date under these 10 posts, and then the post associating to that new date. How can I transform my loop to think that way without hard-coding dates?</p> <p>Thanks</p>
[ { "answer_id": 274211, "author": "dbeja", "author_id": 9585, "author_profile": "https://wordpress.stackexchange.com/users/9585", "pm_score": 1, "selected": false, "text": "<p>You can save the last date on a variable and on each iteration you compare the current date with the last date, a...
2017/07/21
[ "https://wordpress.stackexchange.com/questions/274206", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98671/" ]
The following loop works great for me in getting posts with a given date with the use of the\_time(...): ``` <?php $myPost = new WP_Query( array( 'posts_per_page' => '50', 'orderby' => 'modified', 'order' => 'DESC' )); while ($myPost->have_posts()): $myPost->the_post(); ?> <div class="timeline-group"> <p class="modified-time"><?php the_time('F j, Y') ?></p> <h5><a href="<?php the_permalink();?>"><?php the_title();?></a></h5> </div> <?php endwhile; //Reset Post Data wp_reset_postdata(); ?> ``` But the first 10 posts always show the same date (i.e. July 21, 2017). I want to display that date only once for these 10 posts. And if I create a new post tomorrow, then it should then show a new date under these 10 posts, and then the post associating to that new date. How can I transform my loop to think that way without hard-coding dates? Thanks
Just use `the_date()`, it has this as a built-in feature. See the [dev docs](https://developer.wordpress.org/reference/functions/the_date/) for more info.
274,259
<p>I am developing a wordpress page template exactly like <a href="https://blog.squarespace.com/blog/introducing-promotional-pop-ups" rel="nofollow noreferrer">this</a>. I have completed the design and have loaded the template once user goes to this page which using my template. I want to all posts in more article list open in this template without refreshing the page. but when i click on any post in the list it opens in a new page which is off course different from my page template. Please guide me how i can open the posts in the "more article" list open in my template. Here is my code i have till now.</p> <pre><code>&lt;?php if ( have_posts() ): while ( have_posts() ) : the_post(); ?&gt; &lt;div id="main" class="left-half" style=" background-image: url(&lt;?php echo intrigue_get_attachment(); ?&gt;); width:50%; display: inline-block; float: right; position: fixed; "&gt; &lt;h2 style="diplay:inline-block"&gt;&lt;a href="&lt;?php echo esc_url( home_url( '/' ) );?&gt;"&gt;&lt;?php bloginfo( 'name' );?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;input id="morearticlesbtn" class="button" type="button" onclick="openNav()" value="More Articles "&gt; &lt;div class="row"&gt; &lt;div class="post-meta col-md-6"&gt; &lt;p&gt;July 18, 2017&lt;/p&gt; By: &lt;a href="#"&gt;James Crock &lt;/a&gt; &lt;a href="#"&gt; Transport&lt;/a&gt; &lt;/div&gt; &lt;div class="col-md-6"&gt; &lt;div class="line"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="title-div"&gt; &lt;a href="&lt;?php echo the_permalink() ?&gt;"&gt; &lt;h1 class="title"&gt;&lt;?php the_title() ?&gt;&lt;/h1&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-md-9" &gt; &lt;div class="line bottom-line"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-3 bottom-line-text"&gt; &lt;h4&gt;Next&lt;/h4&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="right" class="right-half" style="width: 50%; display: inline-block; float:right;"&gt; &lt;div class=" content-div"&gt; &lt;?php the_content();?&gt; &lt;/div&gt; &lt;div class="tags content-div clear-fix"&gt; &lt;h6&gt;Tags:&lt;/h6&gt; &lt;?php echo get_the_tag_list();?&gt; &lt;!-- &lt;a href="#"&gt;&lt;h6&gt;Promotional&lt;/h6&gt;&lt;/a&gt;&lt;a href="#"&gt;&lt;h6&gt;Pop-Ups&lt;/h6&gt;&lt;/a&gt;--&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; endif; ?&gt; &lt;!-- THE OFFCANVAS MENU --&gt; &lt;div id="mySidenav" class="sidenav menu"&gt; &lt;div class="hidden-menu-div"&gt; &lt;input class="button close-button" type="button" onclick="closeNav()" value="Hide List "&gt; &lt;div&gt; &lt;a href="#"&gt;About&lt;/a&gt; &lt;a href="#"&gt;Services&lt;/a&gt; &lt;a href="#"&gt;Clients&lt;/a&gt; &lt;a href="#"&gt;Contact&lt;/a&gt; &lt;a href="#search"&gt;Search&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query(); $wp_query-&gt;query('posts_per_page=6' . '&amp;paged='.$paged); while ($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post(); ?&gt; &lt;div class="col-sm-6 hiden-cat-post"&gt; &lt;a href="&lt;?php echo the_permalink(); ?&gt;" class="hidden-cat-item"&gt; &lt;div class="hidden-cat-thumbnail" &gt;&lt;?php the_post_thumbnail(array(340, 230))?&gt; &lt;/div&gt; &lt;div class="hidden-cat-item-text"&gt; &lt;h1 class="hidden-cat-item-title"&gt; &lt;?php the_title(); ?&gt; &lt;/h1&gt; &lt;div class="excerpt"&gt;&lt;/div&gt; &lt;div class="hidden-item-meta"&gt;jul 10,2017&lt;/div&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php if ($paged &gt; 1) { ?&gt; &lt;nav id="nav-posts"&gt; &lt;div class="prev"&gt;&lt;?php next_posts_link('&amp;laquo; Previous Posts'); ?&gt;&lt;/div&gt; &lt;div class="next"&gt;&lt;?php previous_posts_link('Newer Posts &amp;raquo;'); ?&gt;&lt;/div&gt; &lt;/nav&gt; &lt;?php } else { ?&gt; &lt;nav id="nav-posts"&gt; &lt;div class="prev"&gt;&lt;?php next_posts_link('&amp;laquo; Previous Posts'); ?&gt;&lt;/div&gt; &lt;/nav&gt; &lt;?php } ?&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;/div&gt; &lt;!-- SCRIPT --&gt; &lt;script&gt; function openNav() { document.getElementById("mySidenav").style.width = "50%"; document.getElementById("main").style.marginLeft = "50%"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; document.getElementById("main").style.marginLeft= "0"; } </code></pre>
[ { "answer_id": 274284, "author": "Abdul Awal Uzzal", "author_id": 31449, "author_profile": "https://wordpress.stackexchange.com/users/31449", "pm_score": -1, "selected": false, "text": "<p>You can simply put your code in single.php if you want all the posts to use this template style.</p...
2017/07/22
[ "https://wordpress.stackexchange.com/questions/274259", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123788/" ]
I am developing a wordpress page template exactly like [this](https://blog.squarespace.com/blog/introducing-promotional-pop-ups). I have completed the design and have loaded the template once user goes to this page which using my template. I want to all posts in more article list open in this template without refreshing the page. but when i click on any post in the list it opens in a new page which is off course different from my page template. Please guide me how i can open the posts in the "more article" list open in my template. Here is my code i have till now. ``` <?php if ( have_posts() ): while ( have_posts() ) : the_post(); ?> <div id="main" class="left-half" style=" background-image: url(<?php echo intrigue_get_attachment(); ?>); width:50%; display: inline-block; float: right; position: fixed; "> <h2 style="diplay:inline-block"><a href="<?php echo esc_url( home_url( '/' ) );?>"><?php bloginfo( 'name' );?></a></h2> <input id="morearticlesbtn" class="button" type="button" onclick="openNav()" value="More Articles "> <div class="row"> <div class="post-meta col-md-6"> <p>July 18, 2017</p> By: <a href="#">James Crock </a> <a href="#"> Transport</a> </div> <div class="col-md-6"> <div class="line"></div> </div> </div> <div class="title-div"> <a href="<?php echo the_permalink() ?>"> <h1 class="title"><?php the_title() ?></h1></a> </div> <div class="row"> <div class="col-md-9" > <div class="line bottom-line"></div> </div> <div class="col-md-3 bottom-line-text"> <h4>Next</h4> </div> </div> </div> <div id="right" class="right-half" style="width: 50%; display: inline-block; float:right;"> <div class=" content-div"> <?php the_content();?> </div> <div class="tags content-div clear-fix"> <h6>Tags:</h6> <?php echo get_the_tag_list();?> <!-- <a href="#"><h6>Promotional</h6></a><a href="#"><h6>Pop-Ups</h6></a>--> </div> </div> <?php endwhile; endif; ?> <!-- THE OFFCANVAS MENU --> <div id="mySidenav" class="sidenav menu"> <div class="hidden-menu-div"> <input class="button close-button" type="button" onclick="closeNav()" value="Hide List "> <div> <a href="#">About</a> <a href="#">Services</a> <a href="#">Clients</a> <a href="#">Contact</a> <a href="#search">Search</a> </div> </div> <?php $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query(); $wp_query->query('posts_per_page=6' . '&paged='.$paged); while ($wp_query->have_posts()) : $wp_query->the_post(); ?> <div class="col-sm-6 hiden-cat-post"> <a href="<?php echo the_permalink(); ?>" class="hidden-cat-item"> <div class="hidden-cat-thumbnail" ><?php the_post_thumbnail(array(340, 230))?> </div> <div class="hidden-cat-item-text"> <h1 class="hidden-cat-item-title"> <?php the_title(); ?> </h1> <div class="excerpt"></div> <div class="hidden-item-meta">jul 10,2017</div> </div> </a> </div> <?php endwhile; ?> <?php if ($paged > 1) { ?> <nav id="nav-posts"> <div class="prev"><?php next_posts_link('&laquo; Previous Posts'); ?></div> <div class="next"><?php previous_posts_link('Newer Posts &raquo;'); ?></div> </nav> <?php } else { ?> <nav id="nav-posts"> <div class="prev"><?php next_posts_link('&laquo; Previous Posts'); ?></div> </nav> <?php } ?> <?php wp_reset_postdata(); ?> </div> <!-- SCRIPT --> <script> function openNav() { document.getElementById("mySidenav").style.width = "50%"; document.getElementById("main").style.marginLeft = "50%"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; document.getElementById("main").style.marginLeft= "0"; } ```
What you are looking for is AJAX navigation. It's not that complicated, however it's not very easy too. I've written a simple example for you, I hope it helps you in your case. An AJAX request has 2 steps, first a front-end request that is sent out by browser when for example a user clicks a link or an element, then a response from the server. If we need to use that response in our website, there is a third step, which is, well... which is using the response in our website! Creating an AJAX request on user's demand ----------------------------------------- If our user clicks a link, we have to stop the browser to navigating to that page. We can achieve this by using a jQuery function, called `preventDefault()`. This will prevent the default action of any element that is bound to it, whether it's a form, or a link. We need to build some custom link, to make sure we don't interfere with other links such as social networks. We'll add a class and an attribute to our navigation links to use it in the AJAX request. To get the next post's data, we use `get_next_post();` and `get_previous_post();`. We need the ID too. So: ``` $next_post = get_next_post(); $prev_post = get_previous_post(); // Check if the post exists if ( $prev_post ) { ?> <div class="prev ajax-link" data-id="<?php echo $prev_post->ID; ?>"><?php _e('&laquo; Previous Posts','text-domain'); ?></div><?php } if ( $next_post ) { ?> <div class="next ajax-link" data-id="<?php echo $next_post->ID; ?>"><?php _e('Newer Posts &raquo;','text-domain'); ?></div><?php } ``` Now, we'll write a jQuery function and disable the click event on our custom link: ``` (function($){ $('.ajax-link').on('click',function(e){ e.preventDefault(); // The rest of the code goes here, check below }); })(jQuery); ``` By using `$(this)` we get the ID of the post which we saved previously in the `data-id`: ``` var postId = $(this).attr('data-id'); ``` Okay now we have the ID, let's create an AJAX request to out yet not written REST endpoint, and put the response in a DIV that is used as the container of our content: ``` $.get( 'http://example.com/prisma/ajax_navigation/', { ajaxid: postId }).done( function( response ) { if ( response.success ) { $( '#content-div' ).innerHTML( response.content ); } }); ``` Which `content-div` is the ID of the `DIV` that holds your content. It's the element's ID, not the class, and must be unique in the entire page. Alright, time to write the server side endpoint. Creating a REST endpoint to return the post's data -------------------------------------------------- Creating a REST endpoint is as easy as the next lines: ``` add_action( 'rest_api_init', function () { //Path to AJAX endpoint register_rest_route( 'prisma', '/ajax_navigation/', array( 'methods' => 'GET', 'callback' => 'ajax_navigation_function' ) ); }); ``` We've made an endpoint at `http://example.com/prisma/ajax_navigation/`. The path is accessible now, but we still need a callback function to return the post's data. ``` function ajax_navigation_function(){ if( isset( $_REQUEST['ajaxid'] ) ){ $post = get_post( $_REQUEST['ajaxid'] ); $data['content'] = $post->post_content; $data['success'] = true; return $data; } } ``` That's it. Now whenever a user clicks the next post or previous post element, the content of the next or previous post will be fetched via AJAX, and inserted into the DIV element that has the ID of `content-div`. All done.
274,261
<p>I want my theme to have an 'about' page available by default when a user uses my theme.</p> <p>Is there a way to auto create a page when a user selects your template?</p> <p>Or some other way of achieving this?</p>
[ { "answer_id": 274269, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": false, "text": "<p>The wp_insert_post() function is where to start <a href=\"https://developer.wordpress.org/reference/fu...
2017/07/22
[ "https://wordpress.stackexchange.com/questions/274261", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105958/" ]
I want my theme to have an 'about' page available by default when a user uses my theme. Is there a way to auto create a page when a user selects your template? Or some other way of achieving this?
There is a hook specifically for this purpose, called [`after_switch_theme`](https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme). You can hook into it and create your personal page after theme activation. Have a look at this: ``` add_action( 'after_switch_theme', 'create_page_on_theme_activation' ); function create_page_on_theme_activation(){ // Set the title, template, etc $new_page_title = __('About Us','text-domain'); // Page's title $new_page_content = ''; // Content goes here $new_page_template = 'page-custom-page.php'; // The template to use for the page $page_check = get_page_by_title($new_page_title); // Check if the page already exists // Store the above data in an array $new_page = array( 'post_type' => 'page', 'post_title' => $new_page_title, 'post_content' => $new_page_content, 'post_status' => 'publish', 'post_author' => 1, 'post_name' => 'about-us' ); // If the page doesn't already exist, create it if(!isset($page_check->ID)){ $new_page_id = wp_insert_post($new_page); if(!empty($new_page_template)){ update_post_meta($new_page_id, '_wp_page_template', $new_page_template); } } } ``` I suggest you use a unique slug to make sure the code always functions properly, since pages with slugs like `about-us` are very common, and might already exist but don't belong to your theme.
274,277
<p>Someone made a website for me using wordpress.org. They said that they used "Wordpress Framework".</p> <p>Although I haven't changed anything, the logo of the website (which was an image near the top of the homepage is now missing. Not sure how it could disappear without me changing anything, but I am trying to rectify this myself. I am not familiar with wordpress and so am hoping I can find some assistance; at least an idea of where to begin.</p> <p>When I look what the active theme is, it just says 'Yescorts" which is the name of the website (yescorts.co.uk). I'm guessing that the creator customised an existing theme and then changed the name.</p> <p>I know I will probably get down-voted for being vague, but if I knew enough to be specific, I would be able to fix this already. I'm just looking for some suggestions of where I start looking to fix this. Or what more info I can provide to help you help me.</p> <p>Thanks in advance of any advice received. </p>
[ { "answer_id": 274269, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": false, "text": "<p>The wp_insert_post() function is where to start <a href=\"https://developer.wordpress.org/reference/fu...
2017/07/22
[ "https://wordpress.stackexchange.com/questions/274277", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123873/" ]
Someone made a website for me using wordpress.org. They said that they used "Wordpress Framework". Although I haven't changed anything, the logo of the website (which was an image near the top of the homepage is now missing. Not sure how it could disappear without me changing anything, but I am trying to rectify this myself. I am not familiar with wordpress and so am hoping I can find some assistance; at least an idea of where to begin. When I look what the active theme is, it just says 'Yescorts" which is the name of the website (yescorts.co.uk). I'm guessing that the creator customised an existing theme and then changed the name. I know I will probably get down-voted for being vague, but if I knew enough to be specific, I would be able to fix this already. I'm just looking for some suggestions of where I start looking to fix this. Or what more info I can provide to help you help me. Thanks in advance of any advice received.
There is a hook specifically for this purpose, called [`after_switch_theme`](https://codex.wordpress.org/Plugin_API/Action_Reference/after_switch_theme). You can hook into it and create your personal page after theme activation. Have a look at this: ``` add_action( 'after_switch_theme', 'create_page_on_theme_activation' ); function create_page_on_theme_activation(){ // Set the title, template, etc $new_page_title = __('About Us','text-domain'); // Page's title $new_page_content = ''; // Content goes here $new_page_template = 'page-custom-page.php'; // The template to use for the page $page_check = get_page_by_title($new_page_title); // Check if the page already exists // Store the above data in an array $new_page = array( 'post_type' => 'page', 'post_title' => $new_page_title, 'post_content' => $new_page_content, 'post_status' => 'publish', 'post_author' => 1, 'post_name' => 'about-us' ); // If the page doesn't already exist, create it if(!isset($page_check->ID)){ $new_page_id = wp_insert_post($new_page); if(!empty($new_page_template)){ update_post_meta($new_page_id, '_wp_page_template', $new_page_template); } } } ``` I suggest you use a unique slug to make sure the code always functions properly, since pages with slugs like `about-us` are very common, and might already exist but don't belong to your theme.
274,278
<p>I have a <code>page.php</code> in which I am defining a custom sub-menu to pass to <code>header.php</code>.</p> <p>I've tried using a constant (clumsy, I know): </p> <pre><code>define("CUSTOM_MENU", "&lt;ul&gt;&lt;li&gt;Test&lt;/li&gt;&lt;/ul&gt;"); </code></pre> <p>right after this, the code is including the header:</p> <pre><code>get_header(); </code></pre> <p>In the header.php file, where the sub menu is, I am outputting either the custom sub-menu (if set), or a <code>wp_nav_menu</code>:</p> <pre><code>if (defined("CUSTOM_MENU")) echo constant("CUSTOM_MENU"); else wp_nav_menu(array(some stuff)); </code></pre> <p>bizarrely though, the <code>CUSTOM_MENU</code> constant becomes empty the moment <code>get_header()</code> gets called - and stays empty for the rest of <code>page.php</code>:</p> <pre><code> define("CUSTOM_MENU", "&lt;ul&gt;&lt;li&gt;Test&lt;/li&gt;&lt;/ul&gt;"); echo constant("CUSTOM_MENU"); // The HTML code above get_header(); echo constant("CUSTOM_MENU"); // Null! </code></pre> <p>This happens for <em>any</em> method of storing the custom menu data that I use. I have tried:</p> <ul> <li>Different constant names</li> <li>Namespaced constants</li> <li>Global variables</li> <li>A function with a static variable</li> </ul> <p>I can't get my head around why this would happen! If <code>get_header()</code> somehow was including header.php using the http wrapper, then the value wouldn't be unset once we exit <code>get_header()</code> again.</p> <p>What is going on here? Am I overlooking something obvious?</p>
[ { "answer_id": 274322, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>There is most likely an issue of load order. The <code>get_header()</code> function does included your <cod...
2017/07/22
[ "https://wordpress.stackexchange.com/questions/274278", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/2161/" ]
I have a `page.php` in which I am defining a custom sub-menu to pass to `header.php`. I've tried using a constant (clumsy, I know): ``` define("CUSTOM_MENU", "<ul><li>Test</li></ul>"); ``` right after this, the code is including the header: ``` get_header(); ``` In the header.php file, where the sub menu is, I am outputting either the custom sub-menu (if set), or a `wp_nav_menu`: ``` if (defined("CUSTOM_MENU")) echo constant("CUSTOM_MENU"); else wp_nav_menu(array(some stuff)); ``` bizarrely though, the `CUSTOM_MENU` constant becomes empty the moment `get_header()` gets called - and stays empty for the rest of `page.php`: ``` define("CUSTOM_MENU", "<ul><li>Test</li></ul>"); echo constant("CUSTOM_MENU"); // The HTML code above get_header(); echo constant("CUSTOM_MENU"); // Null! ``` This happens for *any* method of storing the custom menu data that I use. I have tried: * Different constant names * Namespaced constants * Global variables * A function with a static variable I can't get my head around why this would happen! If `get_header()` somehow was including header.php using the http wrapper, then the value wouldn't be unset once we exit `get_header()` again. What is going on here? Am I overlooking something obvious?
There is most likely an issue of load order. The `get_header()` function does included your `header.php` file, so I'm not sure what's happening inside that template. One way to figure out is to include it using `include()` and check if the behavior is the same. I would suggest you hook into the `wp_head` or `init` and define your constant there. ``` add_action('init', 'define_my_constant' ); function define_my_constant() { if ( ! defined( 'CUSTOM_MENU' ) && is_page() ) { define('CUSTOM_MENU', '<ul><li>Test</li></ul>'); } } ``` `init` is one of the earliest hooks that runs on WordPress, so your constant should be accessible in any theme or plugins at that point.
274,294
<p>I have some code that returns the latest 5 images from the WordPress Media Library:</p> <pre><code>&lt;?php $excluded = array(1,35,37); $args = array( 'post_type' =&gt; 'attachment', 'numberposts' =&gt; '5', 'category__not_in' =&gt; $excluded ); $images = get_posts($args); if (!empty($images)) { ?&gt; &lt;div class="wrap"&gt; &lt;h5&gt;&lt;span&gt;Recently&lt;/span&gt; Added&lt;/h5&gt; &lt;ul&gt; &lt;?php foreach ($images as $image) { $attachment_link = get_attachment_link( $image-&gt;ID ); echo "&lt;li&gt;&lt;a href='".$attachment_link."'&gt;".wp_get_attachment_image($image-&gt;ID)."&lt;/a&gt;&lt;/li&gt;"; } ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p>I'm excluding some categories that I do not want to display (1,35,37). This works, but sometimes I have multiple categories assigned in addition to the excluded categories...if category 1 is selected and category 15 is selected the image will not show because category 1 is selected.</p> <p>What I am trying to do is exclude the categories only if those categories are selected by themselves. If they are selected with another category that isn't excluded they should show. So, an image that has category 1 and category 12 selected should still show because category 12 is not part of my excluded list.</p> <p>Can anyone point me in the right direction?</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 274322, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>There is most likely an issue of load order. The <code>get_header()</code> function does included your <cod...
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274294", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I have some code that returns the latest 5 images from the WordPress Media Library: ``` <?php $excluded = array(1,35,37); $args = array( 'post_type' => 'attachment', 'numberposts' => '5', 'category__not_in' => $excluded ); $images = get_posts($args); if (!empty($images)) { ?> <div class="wrap"> <h5><span>Recently</span> Added</h5> <ul> <?php foreach ($images as $image) { $attachment_link = get_attachment_link( $image->ID ); echo "<li><a href='".$attachment_link."'>".wp_get_attachment_image($image->ID)."</a></li>"; } ?> </ul> </div> <?php } ?> ``` I'm excluding some categories that I do not want to display (1,35,37). This works, but sometimes I have multiple categories assigned in addition to the excluded categories...if category 1 is selected and category 15 is selected the image will not show because category 1 is selected. What I am trying to do is exclude the categories only if those categories are selected by themselves. If they are selected with another category that isn't excluded they should show. So, an image that has category 1 and category 12 selected should still show because category 12 is not part of my excluded list. Can anyone point me in the right direction? Thanks, Josh
There is most likely an issue of load order. The `get_header()` function does included your `header.php` file, so I'm not sure what's happening inside that template. One way to figure out is to include it using `include()` and check if the behavior is the same. I would suggest you hook into the `wp_head` or `init` and define your constant there. ``` add_action('init', 'define_my_constant' ); function define_my_constant() { if ( ! defined( 'CUSTOM_MENU' ) && is_page() ) { define('CUSTOM_MENU', '<ul><li>Test</li></ul>'); } } ``` `init` is one of the earliest hooks that runs on WordPress, so your constant should be accessible in any theme or plugins at that point.
274,295
<p>I try to change WordPress Twenty-sixteen them.</p> <p>I check the CSS carefully, can't finger out how could be the main menu display on the right of logo(and name of website).</p> <p>No float, no inline-block.</p> <p>I try to add float or display as block to menu and logo, doesn't work at all.How they do it?</p>
[ { "answer_id": 274301, "author": "Rajendra", "author_id": 107649, "author_profile": "https://wordpress.stackexchange.com/users/107649", "pm_score": -1, "selected": false, "text": "<p>In my suggestion, start a child theme of Twenty-sixteen theme,preferred way to Override parent theme func...
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274295", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/18787/" ]
I try to change WordPress Twenty-sixteen them. I check the CSS carefully, can't finger out how could be the main menu display on the right of logo(and name of website). No float, no inline-block. I try to add float or display as block to menu and logo, doesn't work at all.How they do it?
The header of Twenty-Sixteen uses flexbox for alignment. You can set the flex direction of the site-header-main class to column to display the menu under the title/tagline/logo area: ``` .site-header-main { flex-direction: column; } ```
274,296
<p>How can I make it so only members see post summaries on category pages? Currently only members can access them, but they still show up on category pages for non members. </p> <p>Note: I now made a plugin for this, you can get it at: <a href="https://github.com/NerdOfLinux/MemberOnly" rel="nofollow noreferrer">https://github.com/NerdOfLinux/MemberOnly</a></p>
[ { "answer_id": 274301, "author": "Rajendra", "author_id": 107649, "author_profile": "https://wordpress.stackexchange.com/users/107649", "pm_score": -1, "selected": false, "text": "<p>In my suggestion, start a child theme of Twenty-sixteen theme,preferred way to Override parent theme func...
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274296", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123649/" ]
How can I make it so only members see post summaries on category pages? Currently only members can access them, but they still show up on category pages for non members. Note: I now made a plugin for this, you can get it at: <https://github.com/NerdOfLinux/MemberOnly>
The header of Twenty-Sixteen uses flexbox for alignment. You can set the flex direction of the site-header-main class to column to display the menu under the title/tagline/logo area: ``` .site-header-main { flex-direction: column; } ```
274,311
<pre><code>&lt;?php query_posts( array( 'showposts' =&gt; $number, 'nopaging' =&gt; 0, 'download_category' =&gt; $term-&gt;name, 'orderby' =&gt; 'meta_value_num', 'meta_key' =&gt; 'post_views_count', 'order' =&gt; 'DESC', 'post_type' =&gt; array( 'download' ), 'post_status' =&gt; 'publish' ) ); while ( have_posts() ) : the_post(); ?&gt; </code></pre> <p>What this query does is sorting the page with the most views.</p> <p>Now what I want to do is make this into a clickable link, like: "Most Views". Then, when you click on Most views link, the page will sort based on the most views.</p> <p>Edit:</p> <p>I should indeed have provided more information regarding this question: We use a custom music template together with Easy Digital Downloads. <a href="http://www.dl-sounds.com" rel="nofollow noreferrer">http://www.dl-sounds.com</a></p> <p>As you can see there's a widget with "Most Popular". The code I provided comes from this widget. In the middle there's this box with "Newest Audio Files". In this box I want to add a link so it will be possible for visitors to sort the audio by most views.</p> <p>To be exact, I want to add a link in the sorting bar (Browse | Type | Tags) The sorting bar is a php file. </p> <p>I already did some testing with categories. I changed this query with the query above in the category php.</p> <pre><code>&lt;?php /* Genre Query */ query_posts( array( 'post_type' =&gt; 'download', 'posts_per_page' =&gt;'100000', 'download_category' =&gt; $term-&gt;name ) );while ( have_posts() ) : the_post(); ?&gt; </code></pre> <p>This is working fine. If I then browse the categories it is sorted by most views automatically. (on test site)</p>
[ { "answer_id": 274315, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 0, "selected": false, "text": "<p>For executing this query only on user's click action, you can use URL params.</p>\n\n<p>In your template:</p>\n...
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274311", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124411/" ]
``` <?php query_posts( array( 'showposts' => $number, 'nopaging' => 0, 'download_category' => $term->name, 'orderby' => 'meta_value_num', 'meta_key' => 'post_views_count', 'order' => 'DESC', 'post_type' => array( 'download' ), 'post_status' => 'publish' ) ); while ( have_posts() ) : the_post(); ?> ``` What this query does is sorting the page with the most views. Now what I want to do is make this into a clickable link, like: "Most Views". Then, when you click on Most views link, the page will sort based on the most views. Edit: I should indeed have provided more information regarding this question: We use a custom music template together with Easy Digital Downloads. <http://www.dl-sounds.com> As you can see there's a widget with "Most Popular". The code I provided comes from this widget. In the middle there's this box with "Newest Audio Files". In this box I want to add a link so it will be possible for visitors to sort the audio by most views. To be exact, I want to add a link in the sorting bar (Browse | Type | Tags) The sorting bar is a php file. I already did some testing with categories. I changed this query with the query above in the category php. ``` <?php /* Genre Query */ query_posts( array( 'post_type' => 'download', 'posts_per_page' =>'100000', 'download_category' => $term->name ) );while ( have_posts() ) : the_post(); ?> ``` This is working fine. If I then browse the categories it is sorted by most views automatically. (on test site)
You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use `pre_get_posts` to modify the main query. ``` function sort_by_views($query) { if ( !is_admin() && $query->is_main_query() && $query->is_home() && isset( $_REQUEST['sort_by_views'] ) ) { $query->set( 'post_type', 'download'); $query->set( 'post_status', 'publish' ); $query->set( 'posts_per_page', $number ); $query->set( 'nopaging', false ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'meta_key', 'post_views_count' ); $query->set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'sort_by_views' ); ``` Now, if you navigate to `http://example.com/?sort_by_views=blabla`, your posts will be ordered by the views count. This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs. One important note ------------------ Do not use `query_posts`. Use `WP_Query` instead. Using `query_posts` will alter the main query's data, which can mess with your content.
274,318
<p>Here are the arguments for my query.</p> <p>The query always shows the same order after every refresh.</p> <p>Explanation to the query: it show only 4 posts of the custom post type <code>projekte</code>. The post has a custom meta field called <code>ecpt_skills</code> and it should check if there is a string in it which is stored in the variable <code>$porjektart</code>. It also should not show the current post. And it should order the query by random. Everything works except the random.</p> <pre><code> $args = array( 'posts_per_page' =&gt; 4, 'post_type' =&gt; 'projekte', 'meta_key' =&gt; 'ecpt_skills', 'meta_value' =&gt; $projektart, 'meta_compare' =&gt; 'LIKE', post__not_in =&gt; array(get_the_ID()), 'orderby'=&gt; 'rand' ); </code></pre> <p>Does somebody know why this happens?</p>
[ { "answer_id": 274315, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 0, "selected": false, "text": "<p>For executing this query only on user's click action, you can use URL params.</p>\n\n<p>In your template:</p>\n...
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274318", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124414/" ]
Here are the arguments for my query. The query always shows the same order after every refresh. Explanation to the query: it show only 4 posts of the custom post type `projekte`. The post has a custom meta field called `ecpt_skills` and it should check if there is a string in it which is stored in the variable `$porjektart`. It also should not show the current post. And it should order the query by random. Everything works except the random. ``` $args = array( 'posts_per_page' => 4, 'post_type' => 'projekte', 'meta_key' => 'ecpt_skills', 'meta_value' => $projektart, 'meta_compare' => 'LIKE', post__not_in => array(get_the_ID()), 'orderby'=> 'rand' ); ``` Does somebody know why this happens?
You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use `pre_get_posts` to modify the main query. ``` function sort_by_views($query) { if ( !is_admin() && $query->is_main_query() && $query->is_home() && isset( $_REQUEST['sort_by_views'] ) ) { $query->set( 'post_type', 'download'); $query->set( 'post_status', 'publish' ); $query->set( 'posts_per_page', $number ); $query->set( 'nopaging', false ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'meta_key', 'post_views_count' ); $query->set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'sort_by_views' ); ``` Now, if you navigate to `http://example.com/?sort_by_views=blabla`, your posts will be ordered by the views count. This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs. One important note ------------------ Do not use `query_posts`. Use `WP_Query` instead. Using `query_posts` will alter the main query's data, which can mess with your content.
274,321
<p>I'm using the ACF plugin and overall it's working great. </p> <p>Expect for one small part:</p> <p>I've got a WYSIWYG text box on a page where I add a few enters, but when I look at the console I get an unexpected token &lt; error:</p> <pre><code>&lt;?php the_field('correctoutput'); ?&gt; </code></pre> <p>WHen I try to use the below part is just breaks:</p> <pre><code>&lt;?php echo the_field('correctoutput'); ?&gt; </code></pre> <p>When I use it also breaks:</p> <pre><code>&lt;?php echo json_encode the_field('correctoutput'); ?&gt; </code></pre> <p>This completely breaks the page:</p> <pre><code>&lt;?php get_field('correctoutput'); ?&gt; </code></pre> <p>It should add some text to a div when it's correct:</p> <pre><code> $('#correcto').innerHTML (&lt;?php the_field('correctoutput'); ?&gt;); </code></pre> <p>I've also used .text</p> <p>The only way it works is to catch it in a variable:</p> <pre><code>&lt;?php $correctoutput = get_post_meta( get_the_ID(), 'correctoutput', true ); ?&gt; </code></pre> <p>and then output it:</p> <pre><code>&lt;?php echo json_encode ($correctoutput); ?&gt; </code></pre> <p>But this will remove the <code>&lt;p&gt;&lt;/p&gt;</code> tags... and that's also what is giving the issue here.</p>
[ { "answer_id": 274315, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 0, "selected": false, "text": "<p>For executing this query only on user's click action, you can use URL params.</p>\n\n<p>In your template:</p>\n...
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274321", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114176/" ]
I'm using the ACF plugin and overall it's working great. Expect for one small part: I've got a WYSIWYG text box on a page where I add a few enters, but when I look at the console I get an unexpected token < error: ``` <?php the_field('correctoutput'); ?> ``` WHen I try to use the below part is just breaks: ``` <?php echo the_field('correctoutput'); ?> ``` When I use it also breaks: ``` <?php echo json_encode the_field('correctoutput'); ?> ``` This completely breaks the page: ``` <?php get_field('correctoutput'); ?> ``` It should add some text to a div when it's correct: ``` $('#correcto').innerHTML (<?php the_field('correctoutput'); ?>); ``` I've also used .text The only way it works is to catch it in a variable: ``` <?php $correctoutput = get_post_meta( get_the_ID(), 'correctoutput', true ); ?> ``` and then output it: ``` <?php echo json_encode ($correctoutput); ?> ``` But this will remove the `<p></p>` tags... and that's also what is giving the issue here.
You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use `pre_get_posts` to modify the main query. ``` function sort_by_views($query) { if ( !is_admin() && $query->is_main_query() && $query->is_home() && isset( $_REQUEST['sort_by_views'] ) ) { $query->set( 'post_type', 'download'); $query->set( 'post_status', 'publish' ); $query->set( 'posts_per_page', $number ); $query->set( 'nopaging', false ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'meta_key', 'post_views_count' ); $query->set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'sort_by_views' ); ``` Now, if you navigate to `http://example.com/?sort_by_views=blabla`, your posts will be ordered by the views count. This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs. One important note ------------------ Do not use `query_posts`. Use `WP_Query` instead. Using `query_posts` will alter the main query's data, which can mess with your content.
274,368
<p>I am trying to show the featured posts in my theme, with a custom field <code>mytheme_featured_post</code> which is 1 on the featured posts. </p> <p>However it does not seem to filter the posts down to only the posts in the meta query. </p> <pre><code>// WP_Query arguments. $featured = array( 'posts_per_page' =&gt; '5', 'meta_query' =&gt; array( array( 'key' =&gt; 'mytheme_featured_post', 'value' =&gt; '1', ), ), ); // The Query. $featured_query = new WP_Query( $featured ); if ( $featured_query -&gt; have_posts() ) { while ( $featured_query -&gt; have_posts() ) : $featured_query -&gt; the_post(); the_title(); endwhile; } </code></pre> <p><strong>Update:</strong> This args are working as intended: </p> <pre><code>// WP_Query arguments. $featured = array( 'posts_per_page' =&gt; '5', 'cat' =&gt; '1', 'meta_key' =&gt; 'mytheme_featured_post', 'meta_value' =&gt; '1', ); </code></pre>
[ { "answer_id": 274315, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 0, "selected": false, "text": "<p>For executing this query only on user's click action, you can use URL params.</p>\n\n<p>In your template:</p>\n...
2017/07/23
[ "https://wordpress.stackexchange.com/questions/274368", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107055/" ]
I am trying to show the featured posts in my theme, with a custom field `mytheme_featured_post` which is 1 on the featured posts. However it does not seem to filter the posts down to only the posts in the meta query. ``` // WP_Query arguments. $featured = array( 'posts_per_page' => '5', 'meta_query' => array( array( 'key' => 'mytheme_featured_post', 'value' => '1', ), ), ); // The Query. $featured_query = new WP_Query( $featured ); if ( $featured_query -> have_posts() ) { while ( $featured_query -> have_posts() ) : $featured_query -> the_post(); the_title(); endwhile; } ``` **Update:** This args are working as intended: ``` // WP_Query arguments. $featured = array( 'posts_per_page' => '5', 'cat' => '1', 'meta_key' => 'mytheme_featured_post', 'meta_value' => '1', ); ```
You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use `pre_get_posts` to modify the main query. ``` function sort_by_views($query) { if ( !is_admin() && $query->is_main_query() && $query->is_home() && isset( $_REQUEST['sort_by_views'] ) ) { $query->set( 'post_type', 'download'); $query->set( 'post_status', 'publish' ); $query->set( 'posts_per_page', $number ); $query->set( 'nopaging', false ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'meta_key', 'post_views_count' ); $query->set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'sort_by_views' ); ``` Now, if you navigate to `http://example.com/?sort_by_views=blabla`, your posts will be ordered by the views count. This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs. One important note ------------------ Do not use `query_posts`. Use `WP_Query` instead. Using `query_posts` will alter the main query's data, which can mess with your content.
274,382
<p>I just finished my blog I made locally and I would like to upload it to the server as it is in my computer, including the posts and the plugins. Is it possible to do it? </p> <p>I already have a WordPress installation in my server.</p>
[ { "answer_id": 274315, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 0, "selected": false, "text": "<p>For executing this query only on user's click action, you can use URL params.</p>\n\n<p>In your template:</p>\n...
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274382", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114684/" ]
I just finished my blog I made locally and I would like to upload it to the server as it is in my computer, including the posts and the plugins. Is it possible to do it? I already have a WordPress installation in my server.
You can add a query string to your URL and then alter the query if that string is set. What I'm going to do is to use `pre_get_posts` to modify the main query. ``` function sort_by_views($query) { if ( !is_admin() && $query->is_main_query() && $query->is_home() && isset( $_REQUEST['sort_by_views'] ) ) { $query->set( 'post_type', 'download'); $query->set( 'post_status', 'publish' ); $query->set( 'posts_per_page', $number ); $query->set( 'nopaging', false ); $query->set( 'orderby', 'meta_value_num' ); $query->set( 'meta_key', 'post_views_count' ); $query->set( 'order', 'DESC' ); } } add_action( 'pre_get_posts', 'sort_by_views' ); ``` Now, if you navigate to `http://example.com/?sort_by_views=blabla`, your posts will be ordered by the views count. This example works for main query on the homepage, but you can change the conditionals to meet any condition, based on your needs. One important note ------------------ Do not use `query_posts`. Use `WP_Query` instead. Using `query_posts` will alter the main query's data, which can mess with your content.
274,383
<p>I'm trying to put a line break in my input text field in customizer. I'm using a sanitization function like this</p> <pre><code>function sanitize_text( $input ) { $allowed_html = array( 'br' =&gt; array(), ); return wp_kses( $input, $allowed_html ); } </code></pre> <p>I also using php strip_tags but neither of them works.<br> Thanks in advance</p>
[ { "answer_id": 274386, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 0, "selected": false, "text": "<p>I tried the code you shared above and everything appears to be working as intended.</p>\n\n<p>Are you sure...
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274383", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124443/" ]
I'm trying to put a line break in my input text field in customizer. I'm using a sanitization function like this ``` function sanitize_text( $input ) { $allowed_html = array( 'br' => array(), ); return wp_kses( $input, $allowed_html ); } ``` I also using php strip\_tags but neither of them works. Thanks in advance
The only way I was able to make it work was that: functions.php ``` function test_customizer( $wp_customize ) { $wp_customize->add_setting( 'themeslug_text_setting_id', array( 'capability' => 'edit_theme_options', 'default' => 'Lorem Ipsum', 'sanitize_callback' => 'sanitize_textarea_field', ) ); $wp_customize->add_control( 'themeslug_text_setting_id', array( 'type' => 'text', 'section' => 'title_tagline', // Add a default or your own section 'label' => __( 'Custom Text' ), 'description' => __( 'This is a custom text box.' ), ) ); } ``` Front (ex. index.php) ``` <?php $themeslug_text_setting_id = get_theme_mod('themeslug_text_setting_id'); if ($themeslug_text_setting_id) { echo nl2br( esc_html( $themeslug_text_setting_id ) ); } ?> ``` The `sanitize_textarea_field` is fundamental here.
274,408
<p><code>the_tags</code> by default is displaying as URL. I need to display it as plain text to insert inside HTML attribute.</p> <pre><code>&lt;?php $tag = the_tags(''); ?&gt; &lt;div class="image-portfolio" data-section="&lt;?php echo $tag ?&gt;"&gt; </code></pre>
[ { "answer_id": 274409, "author": "Viktor", "author_id": 81006, "author_profile": "https://wordpress.stackexchange.com/users/81006", "pm_score": 2, "selected": false, "text": "<p>Ok i figure it out</p>\n\n<pre><code>$tag = get_the_tags();\nforeach($tag as $tags) {\n echo $tags-&gt;name...
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274408", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81006/" ]
`the_tags` by default is displaying as URL. I need to display it as plain text to insert inside HTML attribute. ``` <?php $tag = the_tags(''); ?> <div class="image-portfolio" data-section="<?php echo $tag ?>"> ```
I'm glad you figured it out, but below is a quick semantic alteration (swapping your use of `$tag` singular and `$tags` plural will help it read closer to what it is doing; functionally it is no different). I also added cases for inside and outside the Loop, and a conditional so you don't end up trying to foreach loop when there are no tags. Commented: ---------- ``` //We are inside the Loop here. Other wise we must pass an ID to get_the_tags() //returns array of objects $tags = get_the_tags(); //make sure we have some if ($tags) { //foreach entry in array of tags, access the tag object foreach( $tags as $tag ) { //echo the name field from the tag object echo $tag->name; } } ``` Inside Loop ----------- ``` $tags = get_the_tags(); if ($tags) { foreach( $tags as $tag ) { echo $tag->name; } } ``` Outside Loop: ------------- ``` $id = '10'; $tags = get_the_tags( $id ); if ($tags) { foreach( $tags as $tag ) { echo $tag->name; } } ``` --- Further ------- Inside [the loop](https://codex.wordpress.org/The_Loop), [`get_the_tags()`](https://developer.wordpress.org/reference/functions/get_the_tags/) uses the current post id. Outside of the loop, you need to pass it an id. Either way, it returns an *array* of [`WP_TERM`](https://developer.wordpress.org/reference/classes/wp_term/) *objects* for each term associated with the relevant post. ``` [0] => WP_Term Object ( [term_id] => [name] => [slug] => [term_group] => [term_taxonomy_id] => [taxonomy] => post_tag [description] => [parent] => [count] => ) ``` You could access each value the same way as above, i.e.: ``` $tags = get_the_tags(); if ($tags) { foreach( $tags as $tag ) { echo $tag->term_id; echo $tag->name; echo $tag->slug; echo $tag->term_group; echo $tag->term_taxonomy_id; echo $tag->taxonomy; echo $tag->description; echo $tag->parent; echo $tag->count; } } ```
274,430
<p>I need to get posts belongs to few categories, but it should match following rule.</p> <p>let say I have category ids 100,105 &amp; 106. </p> <p>then I need <code>100 &amp;&amp; ( 105 || 106 )</code> this rule.</p> <p>I know following rules for separate <code>OR</code> &amp; <code>AND</code>, </p> <pre><code>$query = new WP_Query( array( 'cat' =&gt; '100,105,106' ) ); // 100 || 105 || 106 $query = new WP_Query( array( 'category__and' =&gt; array( 100,105,106 ) ) ); // 100 &amp;&amp; 105 &amp;&amp; 106 </code></pre> <p>But I need something like <code>100 &amp;&amp; ( 105 || 106 )</code>. How can I do that with <code>WP_Query</code> ?</p>
[ { "answer_id": 274435, "author": "Janith Chinthana", "author_id": 68403, "author_profile": "https://wordpress.stackexchange.com/users/68403", "pm_score": 1, "selected": false, "text": "<p>Not sure this is the best way, but I have managed to get the desired result set with following <code...
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274430", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68403/" ]
I need to get posts belongs to few categories, but it should match following rule. let say I have category ids 100,105 & 106. then I need `100 && ( 105 || 106 )` this rule. I know following rules for separate `OR` & `AND`, ``` $query = new WP_Query( array( 'cat' => '100,105,106' ) ); // 100 || 105 || 106 $query = new WP_Query( array( 'category__and' => array( 100,105,106 ) ) ); // 100 && 105 && 106 ``` But I need something like `100 && ( 105 || 106 )`. How can I do that with `WP_Query` ?
Not sure this is the best way, but I have managed to get the desired result set with following `$args` parameters. ``` $args['tax_query'] = array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => array(100), ), array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => array(105,106), ), ); ```
274,451
<p>I am very new to wordpress. I installed it on my linux server lately and uploaded a them on it. Everything looks good on my browser however if I try to access the website outside my network I am only getting the Text and not the CSS. I have read all different forum for the fix bt my problem still there. Here is my .htaccess</p> <pre><code># BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>I have changed the permission to 755 and 777 restarted apache but still same issue.</p>
[ { "answer_id": 274456, "author": "Chris Pink", "author_id": 57686, "author_profile": "https://wordpress.stackexchange.com/users/57686", "pm_score": 0, "selected": false, "text": "<p>Check you are addressing the CSS file correctly. How is it being called?</p>\n\n<p>The url should be along...
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274451", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124482/" ]
I am very new to wordpress. I installed it on my linux server lately and uploaded a them on it. Everything looks good on my browser however if I try to access the website outside my network I am only getting the Text and not the CSS. I have read all different forum for the fix bt my problem still there. Here is my .htaccess ``` # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` I have changed the permission to 755 and 777 restarted apache but still same issue.
Check you are addressing the CSS file correctly. How is it being called? The url should be along the lines of `ht|tp://yoursite.com/wordpress/wp-content/themes/yourtheme/style.css` you'll find somewhere that it's loading as `ht|tp://localhost/`and so it will load correctly on your machine but not on anyone else's. Have a look in Developer Tools for the URL of style.css
274,465
<p>I want to be able to create a shortcode that will return the post title when I pass in the ID of the post. I.E. [myshortcode_title ID=1234]</p> <p>I have a shortcode that pulls the post title from the current post: </p> <pre><code>function myshortcode_title( ){ return get_the_title(); } add_shortcode( 'page_title', 'myshortcode_title' ); </code></pre> <p>I've seen shortcodes that can pass in attributes and return a result outside the loop, but I'm still new at WP shortcodes. </p>
[ { "answer_id": 274456, "author": "Chris Pink", "author_id": 57686, "author_profile": "https://wordpress.stackexchange.com/users/57686", "pm_score": 0, "selected": false, "text": "<p>Check you are addressing the CSS file correctly. How is it being called?</p>\n\n<p>The url should be along...
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274465", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124490/" ]
I want to be able to create a shortcode that will return the post title when I pass in the ID of the post. I.E. [myshortcode\_title ID=1234] I have a shortcode that pulls the post title from the current post: ``` function myshortcode_title( ){ return get_the_title(); } add_shortcode( 'page_title', 'myshortcode_title' ); ``` I've seen shortcodes that can pass in attributes and return a result outside the loop, but I'm still new at WP shortcodes.
Check you are addressing the CSS file correctly. How is it being called? The url should be along the lines of `ht|tp://yoursite.com/wordpress/wp-content/themes/yourtheme/style.css` you'll find somewhere that it's loading as `ht|tp://localhost/`and so it will load correctly on your machine but not on anyone else's. Have a look in Developer Tools for the URL of style.css
274,493
<p>How can you ensure a given plugin is run <em>last</em> before the page finishes rendering?</p> <p>Can it be ensured?</p> <p>Specifically, I am writing a plugin that I want to post-process all content of a given post/page (after any formatting, extra links, ad injections, etc). The rest of the blog doesn't need to be processed - just posts &amp; pages. </p>
[ { "answer_id": 274495, "author": "WPExplorer", "author_id": 68694, "author_profile": "https://wordpress.stackexchange.com/users/68694", "pm_score": 3, "selected": true, "text": "<p>You'll want to hook into \"the_content\" filter at a very high priority. Example:</p>\n\n<pre><code>functio...
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274493", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5173/" ]
How can you ensure a given plugin is run *last* before the page finishes rendering? Can it be ensured? Specifically, I am writing a plugin that I want to post-process all content of a given post/page (after any formatting, extra links, ad injections, etc). The rest of the blog doesn't need to be processed - just posts & pages.
You'll want to hook into "the\_content" filter at a very high priority. Example: ``` function my_alter_the_content( $content ) { if ( in_array( get_post_type(), array( 'post', 'page' ) ) ) { // Do stuff here for posts and pages } return $content; } add_action( 'the_content', 'my_alter_the_content', PHP_INT_MAX ``` ); Using the PHP\_INT\_MAX constant for the hook priority you can ensure it runs as last as possible (most plugins/themes will just use the default priority of 10). The issue is when you say "after all ad injections...etc" that really depends how things are being added. Because if there are ads being added via javascript then of course the only way to override it would be via javascript.
274,496
<p>I'm using the following to add specific classes to my odd/even posts but I also need to add a class to all posts except the first one. Is there a quick, semantic way to do this minus the first post?</p> <pre><code>&lt;?php $homenews_query = new WP_Query( 'posts_per_page=4' ); ?&gt; &lt;?php while ($homenews_query -&gt; have_posts()) : $homenews_query -&gt; the_post(); ?&gt; &lt;?php if ($homenews_query-&gt;current_post % 2 == 0): ?&gt; &lt;!-- stuff here --&gt; &lt;?php else: ?&gt; &lt;!-- stuff here --&gt; &lt;?php endif ?&gt; &lt;?php endwhile; wp_reset_postdata(); ?&gt; </code></pre> <p>I've tried various ways to do this--mostly with jQuery (addClass and removeClass) and it's not been working for me. </p> <p>TIA!</p>
[ { "answer_id": 274498, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 2, "selected": true, "text": "<p>You can do this in multiple ways, but you will need something commom to all posts, exemple:...
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274496", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/7662/" ]
I'm using the following to add specific classes to my odd/even posts but I also need to add a class to all posts except the first one. Is there a quick, semantic way to do this minus the first post? ``` <?php $homenews_query = new WP_Query( 'posts_per_page=4' ); ?> <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php endwhile; wp_reset_postdata(); ?> ``` I've tried various ways to do this--mostly with jQuery (addClass and removeClass) and it's not been working for me. TIA!
You can do this in multiple ways, but you will need something commom to all posts, exemple: ``` <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> ``` then in your **css**: ``` .post:not(:first-child) { // add the rules of the class you wanted to add } ``` Just select all elements except the first-child of posts with the class `post` and add the rules of the class you wanted to add. You also can do with **js/jquery**: ``` $('.post:not(:first-child)').addClass('myclass'); ``` It's the same logic as with css, but if you wnat to add a separate class you can do it. or you can do with **php**: ``` <?php $count = 0 ?> <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($count != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php $count++; endwhile; wp_reset_postdata(); ?> ``` I know that the first post, is the one in the `index 0` so a just check if the count is != 0. or simpler, you have an attribute called `current_post` just check if you're not in the first post, like this: ``` <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($homenews_query->current_post != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php endwhile; wp_reset_postdata(); ?> ``` **Edit: I posted with the inverse logic, fixed now.**
274,515
<p>I have a simple columns shortcode. (How) can this be adjusted to output a containing div around multiple columns? </p> <p>Really don't want to nest shortcodes in the frontend. Perhaps some kind of filter?</p> <p>My <code>functions.php</code> looks like this:</p> <pre><code>// Columns shortcode function abc_custom_column( $atts, $content = null ) { return '&lt;div class="column"&gt;' . do_shortcode( $content ) . '&lt;/div&gt;'; } add_shortcode('col', 'abc_custom_column'); </code></pre> <p>Hoping for something like: </p> <pre><code>if ( 'col' === &gt;2 ) { return '&lt;div class="multi_columns"&gt;' . do_shortcode( $content ) . '&lt;/div&gt;'; } else { return '&lt;div class="column"&gt;' . do_shortcode( $content ) . '&lt;/div&gt;'; } </code></pre> <p>*** I know that clearly won't work / isn't valid code.</p>
[ { "answer_id": 274498, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 2, "selected": true, "text": "<p>You can do this in multiple ways, but you will need something commom to all posts, exemple:...
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274515", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I have a simple columns shortcode. (How) can this be adjusted to output a containing div around multiple columns? Really don't want to nest shortcodes in the frontend. Perhaps some kind of filter? My `functions.php` looks like this: ``` // Columns shortcode function abc_custom_column( $atts, $content = null ) { return '<div class="column">' . do_shortcode( $content ) . '</div>'; } add_shortcode('col', 'abc_custom_column'); ``` Hoping for something like: ``` if ( 'col' === >2 ) { return '<div class="multi_columns">' . do_shortcode( $content ) . '</div>'; } else { return '<div class="column">' . do_shortcode( $content ) . '</div>'; } ``` \*\*\* I know that clearly won't work / isn't valid code.
You can do this in multiple ways, but you will need something commom to all posts, exemple: ``` <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> ``` then in your **css**: ``` .post:not(:first-child) { // add the rules of the class you wanted to add } ``` Just select all elements except the first-child of posts with the class `post` and add the rules of the class you wanted to add. You also can do with **js/jquery**: ``` $('.post:not(:first-child)').addClass('myclass'); ``` It's the same logic as with css, but if you wnat to add a separate class you can do it. or you can do with **php**: ``` <?php $count = 0 ?> <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($count != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php $count++; endwhile; wp_reset_postdata(); ?> ``` I know that the first post, is the one in the `index 0` so a just check if the count is != 0. or simpler, you have an attribute called `current_post` just check if you're not in the first post, like this: ``` <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($homenews_query->current_post != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php endwhile; wp_reset_postdata(); ?> ``` **Edit: I posted with the inverse logic, fixed now.**
274,518
<p>Whenever I search something on my wordpress site, I get the error:</p> <pre><code>Fatal error: Uncaught Error: Call to undefined function get_exID() in /var/www/html/wp-content/themes/twentyseventeen/functions.php:360 Stack trace: #0 /var/www/html/wp-includes/class-wp-hook.php(298): twentyseventeen_excerpt_more(' [&amp;hellip;]') #1 /var/www/html/wp- includes/plugin.php(203): WP_Hook-&gt;apply_filters(' [&amp;hellip;]', Array) #2 /var/www/html/wp-includes/formatting.php(3315): apply_filters('excerpt_more', ' [&amp;hellip;]') #3 /var/www/html/wp- includes/class-wp-hook.php(300): wp_trim_excerpt('&lt;p&gt;Today I will...') #4 /var/www/html/wp-includes/plugin.php(203): WP_Hook- &gt;apply_filters('', Array) #5 /var/www/html/wp-includes/post- template.php(397): apply_filters('get_the_excerpt', '', Object(WP_Post)) #6 /var/www/html/wp-includes/post-template.php(362): get_the_excerpt() #7 /var/www/html/wp- content/themes/twentyseventeen/template-parts/post/content- excerpt.php(43): the_excerpt() #8 /var/www/html/wp- includes/template.php(690): require('/var/www/html/w...') #9 /var/www/html/wp-includes/template.php(647): load_template('/var in /var/www/html/wp-content/themes/twentyseventeen/functions.php on line 360 </code></pre> <p>where the post summary is supposed to be. How can I fix it?</p>
[ { "answer_id": 274498, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 2, "selected": true, "text": "<p>You can do this in multiple ways, but you will need something commom to all posts, exemple:...
2017/07/24
[ "https://wordpress.stackexchange.com/questions/274518", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123649/" ]
Whenever I search something on my wordpress site, I get the error: ``` Fatal error: Uncaught Error: Call to undefined function get_exID() in /var/www/html/wp-content/themes/twentyseventeen/functions.php:360 Stack trace: #0 /var/www/html/wp-includes/class-wp-hook.php(298): twentyseventeen_excerpt_more(' [&hellip;]') #1 /var/www/html/wp- includes/plugin.php(203): WP_Hook->apply_filters(' [&hellip;]', Array) #2 /var/www/html/wp-includes/formatting.php(3315): apply_filters('excerpt_more', ' [&hellip;]') #3 /var/www/html/wp- includes/class-wp-hook.php(300): wp_trim_excerpt('<p>Today I will...') #4 /var/www/html/wp-includes/plugin.php(203): WP_Hook- >apply_filters('', Array) #5 /var/www/html/wp-includes/post- template.php(397): apply_filters('get_the_excerpt', '', Object(WP_Post)) #6 /var/www/html/wp-includes/post-template.php(362): get_the_excerpt() #7 /var/www/html/wp- content/themes/twentyseventeen/template-parts/post/content- excerpt.php(43): the_excerpt() #8 /var/www/html/wp- includes/template.php(690): require('/var/www/html/w...') #9 /var/www/html/wp-includes/template.php(647): load_template('/var in /var/www/html/wp-content/themes/twentyseventeen/functions.php on line 360 ``` where the post summary is supposed to be. How can I fix it?
You can do this in multiple ways, but you will need something commom to all posts, exemple: ``` <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> ``` then in your **css**: ``` .post:not(:first-child) { // add the rules of the class you wanted to add } ``` Just select all elements except the first-child of posts with the class `post` and add the rules of the class you wanted to add. You also can do with **js/jquery**: ``` $('.post:not(:first-child)').addClass('myclass'); ``` It's the same logic as with css, but if you wnat to add a separate class you can do it. or you can do with **php**: ``` <?php $count = 0 ?> <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($count != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php $count++; endwhile; wp_reset_postdata(); ?> ``` I know that the first post, is the one in the `index 0` so a just check if the count is != 0. or simpler, you have an attribute called `current_post` just check if you're not in the first post, like this: ``` <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($homenews_query->current_post != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php endwhile; wp_reset_postdata(); ?> ``` **Edit: I posted with the inverse logic, fixed now.**
274,553
<p>I am new to WordPress development. After develops a simple from the scratch everything works fine. Now I want to create a custom page template to show case all e-books with a just thumbnail of the cover and the price. To brief description, I want to redirect to a particular page. It's all like from the Blog list to particular blog page.</p> <p>I created the custom page with specific style. Now my problem is I don't know how to redirect to its particular page for purchase.</p> <p>How do I do that? Any instruction will be helpful. Thanks in Advance.</p>
[ { "answer_id": 274498, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 2, "selected": true, "text": "<p>You can do this in multiple ways, but you will need something commom to all posts, exemple:...
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274553", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124542/" ]
I am new to WordPress development. After develops a simple from the scratch everything works fine. Now I want to create a custom page template to show case all e-books with a just thumbnail of the cover and the price. To brief description, I want to redirect to a particular page. It's all like from the Blog list to particular blog page. I created the custom page with specific style. Now my problem is I don't know how to redirect to its particular page for purchase. How do I do that? Any instruction will be helpful. Thanks in Advance.
You can do this in multiple ways, but you will need something commom to all posts, exemple: ``` <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> <div class="post"></div> ``` then in your **css**: ``` .post:not(:first-child) { // add the rules of the class you wanted to add } ``` Just select all elements except the first-child of posts with the class `post` and add the rules of the class you wanted to add. You also can do with **js/jquery**: ``` $('.post:not(:first-child)').addClass('myclass'); ``` It's the same logic as with css, but if you wnat to add a separate class you can do it. or you can do with **php**: ``` <?php $count = 0 ?> <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($count != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php $count++; endwhile; wp_reset_postdata(); ?> ``` I know that the first post, is the one in the `index 0` so a just check if the count is != 0. or simpler, you have an attribute called `current_post` just check if you're not in the first post, like this: ``` <?php while ($homenews_query -> have_posts()) : $homenews_query -> the_post(); ?> <?php if ($homenews_query->current_post != 0): ?> <!-- stuff here --> <?php endif ?> <?php if ($homenews_query->current_post % 2 == 0): ?> <!-- stuff here --> <?php else: ?> <!-- stuff here --> <?php endif ?> <?php endwhile; wp_reset_postdata(); ?> ``` **Edit: I posted with the inverse logic, fixed now.**
274,559
<p>I'm coding a plugin that adds a filter to <code>single_template</code>. The filter function successfully returns the path to my <code>show-post-in-a-lightbox.php</code> template.</p> <p>As you can guess from its name, my template is intended to show a single post in a lightbox. Therefore I need to show only the post content and avoid the title bar, menus, sidebars, footers and so on. However, for the post content to show correctly, I need the usual <code>&lt;head&gt;</code> section with all the <code>&lt;link&gt;</code> tags to the required stylesheets and <code>&lt;script&gt;</code> tags.</p> <p>My template code so far is:</p> <pre><code>&lt;?php /* Template Name: show-post-in-lightbox * */ get_header(); ?&gt; &lt;div id="primary" class="content-area"&gt; &lt;main id="main" class="site-main" role="main"&gt; &lt;?php global $post; // Start the loop. while ( have_posts() ) : the_post(); $content = $post-&gt;post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]&gt;', ']]&amp;gt;', $content); echo $content; </code></pre> <p>This works in that it shows the post content, but it also shows the heading banner above it, with the site logo, the title (I'm not talking about <code>&lt;title&gt;</code>, that one is ok, but I mean <code>&lt;header id="masthead" class="site-header"&gt;</code>), and all the rest therein.</p> <p>If I comment out the <code>get_header();</code> line it outputs only the content, but without the required styles and scripts.</p> <p>Is there a function that returns (or outputs) only the <code>&lt;head&gt;</code> tag (or only up to the <code>&lt;/head&gt;</code> tag) of a given post?</p>
[ { "answer_id": 274562, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>You can use the <code>wp_head()</code> function, you just need to add the opening <code>html</code> and...
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274559", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/84622/" ]
I'm coding a plugin that adds a filter to `single_template`. The filter function successfully returns the path to my `show-post-in-a-lightbox.php` template. As you can guess from its name, my template is intended to show a single post in a lightbox. Therefore I need to show only the post content and avoid the title bar, menus, sidebars, footers and so on. However, for the post content to show correctly, I need the usual `<head>` section with all the `<link>` tags to the required stylesheets and `<script>` tags. My template code so far is: ``` <?php /* Template Name: show-post-in-lightbox * */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php global $post; // Start the loop. while ( have_posts() ) : the_post(); $content = $post->post_content; $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]&gt;', $content); echo $content; ``` This works in that it shows the post content, but it also shows the heading banner above it, with the site logo, the title (I'm not talking about `<title>`, that one is ok, but I mean `<header id="masthead" class="site-header">`), and all the rest therein. If I comment out the `get_header();` line it outputs only the content, but without the required styles and scripts. Is there a function that returns (or outputs) only the `<head>` tag (or only up to the `</head>` tag) of a given post?
I've finally ended up with something similar to what Mark Kaplun had suggested in his answer, but, instead of using JS code, I opted for a CSS solution instead. When my code creates the `<iframe>` link, it appends a extra HTTP parameter: ``` $lightboxlink = '/?p='.$postid.'&use-lightbox-css=1'; ``` Then the plugin checks for that parameter, and, if present, it enqueues the extra CSS file. And here is the CSS file contents: ``` header { display: none !important; } ``` I know, I shouldn't be using `!important`. To avoid that, the plugin uses the lowest possible prority (PHP\_INT\_MAX) to the `add_action` call that register my function with the `wp_enqueue_style` call. That way, my extra CSS is loaded as the last one inside the `<iframe>` tag and it takes precedence over all the others (that's the `Cascading` meaning of CSS). Now I can strip the `!important`: ``` header { display: none; } ``` That works only with themes that actually make use of the `<header>` tag, but for now it's good enough for my use cases. Anyway adapting it to other themes is only a matter of adding the required selectors to the CSS file, for example here is a first guess for the Wiz theme that I sometimes use: ``` header, .header-vh-wrapper, .navbar-inner, .nav-container, .logo, #title { display: none; } ```
274,561
<p>I created text widget and wordpress created some default styles it uses h2 tag and class "widgettitle". How can i change tag to h1 and remove class from it.</p> <p>This is my function.php file</p> <pre><code>function home_consultation_init() { register_sidebar(array( "name" =&gt; "Home Consulatation", "id" =&gt; "home_consult", "before_widget" =&gt; "", "after_widget" =&gt; "", "before-title" =&gt; "", "after-title" =&gt; "" )); } </code></pre>
[ { "answer_id": 274566, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>The <code>before-title</code> and <code>after-title</code> arguments passed to <code>register_sidebar()<...
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274561", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124458/" ]
I created text widget and wordpress created some default styles it uses h2 tag and class "widgettitle". How can i change tag to h1 and remove class from it. This is my function.php file ``` function home_consultation_init() { register_sidebar(array( "name" => "Home Consulatation", "id" => "home_consult", "before_widget" => "", "after_widget" => "", "before-title" => "", "after-title" => "" )); } ```
The `before-title` and `after-title` arguments passed to `register_sidebar()` need to use underscores: ``` register_sidebar(array( "name" => "Home Consulatation", "id" => "home_consult", "before_widget" => "", "after_widget" => "", "before_title" => "", "after_title" => "" )); ``` If you use that the titles won't have any tags. You need to provide them to the `before_title` and `after_title` arguments, like so: ``` register_sidebar(array( "name" => "Home Consulatation", "id" => "home_consult", "before_widget" => "", "after_widget" => "", "before_title" => "<h1>", "after_title" => "</h1>" )); ``` Your problem was that you were using the incorrect keys (with `-` instead of `_`), so it was using the defaults.
274,569
<p>I want to add custom PHP code to ensure that whenever a page on my site loads in my browser, the URL of that page is echoed to the screen. I can use <code>echo get_permalink()</code>, but that does not work on all pages. Some pages (e.g. <a href="https://www.horizonhomes-samui.com/" rel="noreferrer">my homepage</a>) display several posts, and if I use <code>get_permalink()</code> on these pages, the URL of the displayed page is not returned (I believe it returns the URL of the last post in the loop). For these pages, how can I return the URL?</p> <p>Can I attach <code>get_permalink()</code> to a particular hook that fires before the loop is executed? Or can I somehow break out of the loop, or reset it once it is complete?</p> <p>Thanks.</p>
[ { "answer_id": 274572, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 9, "selected": true, "text": "<p><code>get_permalink()</code> is only really useful for single pages and posts, and only works inside the...
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274569", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/51204/" ]
I want to add custom PHP code to ensure that whenever a page on my site loads in my browser, the URL of that page is echoed to the screen. I can use `echo get_permalink()`, but that does not work on all pages. Some pages (e.g. [my homepage](https://www.horizonhomes-samui.com/)) display several posts, and if I use `get_permalink()` on these pages, the URL of the displayed page is not returned (I believe it returns the URL of the last post in the loop). For these pages, how can I return the URL? Can I attach `get_permalink()` to a particular hook that fires before the loop is executed? Or can I somehow break out of the loop, or reset it once it is complete? Thanks.
`get_permalink()` is only really useful for single pages and posts, and only works inside the loop. The simplest way I've seen is this: ``` global $wp; echo home_url( $wp->request ) ``` `$wp->request` includes the path part of the URL, eg. `/path/to/page` and `home_url()` outputs the URL in Settings > General, but you can append a path to it, so we're appending the request path to the home URL in this code. Note that this probably won't work with Permalinks set to Plain, and will leave off query strings (the `?foo=bar` part of the URL). To get the URL when permalinks are set to plain you can use `$wp->query_vars` instead, by passing it to `add_query_arg()`: ``` global $wp; echo add_query_arg( $wp->query_vars, home_url() ); ``` And you could combine these two methods to get the current URL, including the query string, regardless of permalink settings: ``` global $wp; echo add_query_arg( $wp->query_vars, home_url( $wp->request ) ); ```
274,576
<p>I am having a problem when creating scheduled posts. I create the posts as normal, click edit, set a scheduled time and click ok then the shedual button. Soon as i do this i check the website and the post has been published immediately. I looked back in the view all posts page and the post says its still scheduled. It was working fine for months but suddenly this is occurring. Really need this sorting asap! cheers</p>
[ { "answer_id": 274572, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 9, "selected": true, "text": "<p><code>get_permalink()</code> is only really useful for single pages and posts, and only works inside the...
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274576", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122305/" ]
I am having a problem when creating scheduled posts. I create the posts as normal, click edit, set a scheduled time and click ok then the shedual button. Soon as i do this i check the website and the post has been published immediately. I looked back in the view all posts page and the post says its still scheduled. It was working fine for months but suddenly this is occurring. Really need this sorting asap! cheers
`get_permalink()` is only really useful for single pages and posts, and only works inside the loop. The simplest way I've seen is this: ``` global $wp; echo home_url( $wp->request ) ``` `$wp->request` includes the path part of the URL, eg. `/path/to/page` and `home_url()` outputs the URL in Settings > General, but you can append a path to it, so we're appending the request path to the home URL in this code. Note that this probably won't work with Permalinks set to Plain, and will leave off query strings (the `?foo=bar` part of the URL). To get the URL when permalinks are set to plain you can use `$wp->query_vars` instead, by passing it to `add_query_arg()`: ``` global $wp; echo add_query_arg( $wp->query_vars, home_url() ); ``` And you could combine these two methods to get the current URL, including the query string, regardless of permalink settings: ``` global $wp; echo add_query_arg( $wp->query_vars, home_url( $wp->request ) ); ```
274,589
<p>I have a code for display recent posts: </p> <p><code>&lt;?php $args = array( 'numberposts' =&gt; '5' ); $recent_posts = wp_get_recent_posts( $args ); foreach( $recent_posts as $recent ){ echo '&lt;h2&gt;&lt;a href="' . get_permalink($recent["ID"]) . '"&gt;' . $recent["post_title"].'&lt;/a&gt; &lt;/h2&gt; '; echo '&lt;p&gt;' . date_i18n('d F Y', strtotime($recent['post_date'])) .'&lt;/p&gt; '; // what code here? } wp_reset_query(); ?&gt;</code></p> <p>now I want to display category name and link also. What kind of code should I use in here? I try some but without effect...</p> <p>Thx :)</p>
[ { "answer_id": 274591, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>You can use <a href=\"https://codex.wordpress.org/Function_Reference/get_the_category_list\" rel=\"nofol...
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274589", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116847/" ]
I have a code for display recent posts: `<?php $args = array( 'numberposts' => '5' ); $recent_posts = wp_get_recent_posts( $args ); foreach( $recent_posts as $recent ){ echo '<h2><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </h2> '; echo '<p>' . date_i18n('d F Y', strtotime($recent['post_date'])) .'</p> '; // what code here? } wp_reset_query(); ?>` now I want to display category name and link also. What kind of code should I use in here? I try some but without effect... Thx :)
You can use [`get_the_category_list()`](https://codex.wordpress.org/Function_Reference/get_the_category_list) to output a comma-separated list of links to categories: ``` <?php $args = array( 'numberposts' => '5' ); $recent_posts = wp_get_recent_posts( $args ); foreach( $recent_posts as $recent ){ echo '<h2><a href="' . get_permalink($recent["ID"]) . '">' . $recent["post_title"].'</a> </h2> '; echo '<p>' . date_i18n('d F Y', strtotime($recent['post_date'])) .'</p> '; echo get_the_category_list( ', ', '', $recent["ID"] ); } wp_reset_query(); ?> ```
274,592
<p>I am trying to create some kind of repeated fields and for that, I want to create a new wp editor with some unique ID. </p> <p>So my question is there any way to create <code>wp_editor</code> using any js? same as we get using <code>&lt;?php wp_editor() ?&gt;</code> WordPress function.</p> <p>I have tried using </p> <pre><code>tinyMCE .init( { mode : "exact" , elements : "accordion_icon_description_"+response.success.item_count }); </code></pre> <p>but it prints very basic editor which is I think not same as of WordPress post content field editor</p>
[ { "answer_id": 274608, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 4, "selected": true, "text": "<p>Thanks to <a href=\"https://wordpress.stackexchange.com/questions/274592/how-to-create-wp-editor-using-javascri...
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274592", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114894/" ]
I am trying to create some kind of repeated fields and for that, I want to create a new wp editor with some unique ID. So my question is there any way to create `wp_editor` using any js? same as we get using `<?php wp_editor() ?>` WordPress function. I have tried using ``` tinyMCE .init( { mode : "exact" , elements : "accordion_icon_description_"+response.success.item_count }); ``` but it prints very basic editor which is I think not same as of WordPress post content field editor
Thanks to [Jacob Peattie's comment](https://wordpress.stackexchange.com/questions/274592/how-to-create-wp-editor-using-javascript#comment407500_274592) I can answer this using JS only. Actually we did something similar, but prior 4.8 and it wasn't this easy, so we did use `wp_editor()` in the end. But now, you can do so [using `wp.editor` object in JavaScript](https://make.wordpress.org/core/2017/05/20/editor-api-changes-in-4-8/). There are 3 main functions 1. `wp.editor.initialize = function( id, settings ) {` Where `id` is > > The HTML id of the textarea that is used for the editor. > Has to be jQuery compliant. No brackets, special chars, etc. > > > and `settings` is either an object ``` { tinymce: { // tinymce settings }, quicktags: { buttons: '..' } } ``` with these [TinyMCE settings](https://www.tinymce.com/docs/configure/integration-and-setup/). Instead of any of the 3 objects (`settings` itself, `tinymce` or `quicktags`) you can use `true` to use the defaults. 2. `wp.editor.remove = function( id ) {` Is quite self-explanatory. Remove any editor instance that was created via `wp.editor.initialize`. 3. `wp.editor.getContent = function( id ) {` Well, get the content of any editor created via `wp.editor.initialize`. --- Usage could look like so ``` var countEditors = 0; $(document).on('click', 'button#addEditor', function() { var editorId = 'editor-' + countEditors; // add editor in HTML as <textarea> with id editorId // give it class wp-editor wp.editor.initialize(editorId, true); countEditors++; }); $(document).on('click', 'button.removeEditor', function() { // assuming editor is under the same parent var editorId = $(this).parent().find('.wp-editor'); wp.editor.remove(editorId); }); ``` As the content will be automatically posted, it is not needed in this example. But you could always retrieve it via `wp.editor.getContent( editorId )`
274,594
<p>i am getting various casino links on my site, i have searched everywhere in the files in my database, but i can't locate the issue, these links come and go they mostly appear in the header and the footer. After clicking on the link they linked to:</p> <pre><code>http://my/sitehollywood-casino-columbus-jobs/ </code></pre> <p>I have attached a screenshot. Your help is most appreciated. <a href="https://i.stack.imgur.com/R3MiA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R3MiA.png" alt="enter image description here"></a></p>
[ { "answer_id": 274602, "author": "Tony Cecala", "author_id": 124435, "author_profile": "https://wordpress.stackexchange.com/users/124435", "pm_score": 1, "selected": false, "text": "<p>Your site is almost definitely compromised. Doing your own cleanup may not be worth the time and effort...
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274594", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/114702/" ]
i am getting various casino links on my site, i have searched everywhere in the files in my database, but i can't locate the issue, these links come and go they mostly appear in the header and the footer. After clicking on the link they linked to: ``` http://my/sitehollywood-casino-columbus-jobs/ ``` I have attached a screenshot. Your help is most appreciated. [![enter image description here](https://i.stack.imgur.com/R3MiA.png)](https://i.stack.imgur.com/R3MiA.png)
Your site is almost definitely compromised. Doing your own cleanup may not be worth the time and effort because reinfection is likely if you miss a single infected file. At this point I recommend to my clients that they get professional help. You may be able to get more details from a site scan by Sucuri. They have a free remote scan for virus infection. [Site scan by Sucuri](https://sitecheck.sucuri.net/)
274,624
<p>With a plugin I'm trying to develop, I'm trying to place some content on the front-page of the website after the header.</p> <p>In my plugin PHP file I have this (I've cut the html content out to save space):</p> <pre><code>add_action( '__after_header' , 'add_promotional_text', 4 ); function add_promotional_text() { // If we're on the home page, do something if ( ! is_admin() ) { if ( is_front_page() &amp;&amp; is_home() ){ return; //HTML goes here } } } do_action ( '__after_header' ); </code></pre> <p>This almost does what I want it to do. The content is not showing up in the admin area... and it does show up on the front-page like it is supposed to... however, it is also showing up on every page or post, which is not supposed to happen.</p> <p>It would be desirable for it to only show up on the front-page, and not on any other front-end facing pages.</p> <p>I am not sure how to do that.</p> <p>EDIT: </p> <p>I have simplified the plugin code to just this:</p> <pre><code>if ( is_front_page() &amp;&amp; is_home() ){ echo "&lt;script&gt;console.log( 'Debug Objects: is_front_page() &amp;&amp; Home()' );&lt;/script&gt;"; } else { echo "&lt;script&gt;console.log( 'Debug Objects: ! is_front_page() &amp;&amp; Home()' );&lt;/script&gt;"; } </code></pre> <p>And no matter how things are set in Settings > Reading, this if condition is never true. It is always false no matter where I navigate to in the site whether it is the front end or admin area.</p> <p><strong>Settings > Reading:</strong> <a href="https://i.stack.imgur.com/cWQql.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cWQql.png" alt="enter image description here"></a></p> <p><strong>Front Page with console output:</strong> <a href="https://i.stack.imgur.com/22xAd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/22xAd.png" alt="enter image description here"></a></p>
[ { "answer_id": 274629, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>This code appears wrong. Your version was doing a return if the front page or home was true. Change th...
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274624", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/15447/" ]
With a plugin I'm trying to develop, I'm trying to place some content on the front-page of the website after the header. In my plugin PHP file I have this (I've cut the html content out to save space): ``` add_action( '__after_header' , 'add_promotional_text', 4 ); function add_promotional_text() { // If we're on the home page, do something if ( ! is_admin() ) { if ( is_front_page() && is_home() ){ return; //HTML goes here } } } do_action ( '__after_header' ); ``` This almost does what I want it to do. The content is not showing up in the admin area... and it does show up on the front-page like it is supposed to... however, it is also showing up on every page or post, which is not supposed to happen. It would be desirable for it to only show up on the front-page, and not on any other front-end facing pages. I am not sure how to do that. EDIT: I have simplified the plugin code to just this: ``` if ( is_front_page() && is_home() ){ echo "<script>console.log( 'Debug Objects: is_front_page() && Home()' );</script>"; } else { echo "<script>console.log( 'Debug Objects: ! is_front_page() && Home()' );</script>"; } ``` And no matter how things are set in Settings > Reading, this if condition is never true. It is always false no matter where I navigate to in the site whether it is the front end or admin area. **Settings > Reading:** [![enter image description here](https://i.stack.imgur.com/cWQql.png)](https://i.stack.imgur.com/cWQql.png) **Front Page with console output:** [![enter image description here](https://i.stack.imgur.com/22xAd.png)](https://i.stack.imgur.com/22xAd.png)
After turning on WP\_DEBUG, ``` define('WP_DEBUG', true); ``` I was receiving the error: **Conditional query tags do not work before the query is run. Before then, they always return false.** After googling that error, I found a solution that works: ``` add_action( 'template_redirect', 'check_for_frontpage' ); function check_for_frontpage() { if ( is_front_page() || is_home() ) { echo "<script>console.log( 'Debug Objects: is_front_page() && Home()' );</script>"; } else { echo "<script>console.log( 'Debug Objects: ! is_front_page() && Home()' );</script>"; } } ```
274,650
<p>In WordPress, I use a function in functions.php to only not show certain posts(by category) if a user is not signed in:</p> <pre><code> function my_filter( $content ) { $categories = array( 'news', 'opinions', 'sports', 'other', ); if ( in_category( $categories ) ) { if ( is_logged_in() ) { return $content; } else { $content = '&lt;p&gt;Sorry, this post is only available to members&lt;/p&gt; &lt;a href="gateblogs.com/login"&gt; Login &lt;/a&gt;'; return $content; } } else { return $content; } } add_filter( 'the_content', 'my_filter' ); </code></pre> <p>I use a plugin(not important to my question), but basically, I can use something like <code>https://gateblogs.com/login?redirect_to=https%3A%2F%2Fgateblogs.com%2Ftechnology%2Flinux-tutorials%2Fsending-mail-from-server</code> to redirect to a page after a successful login. How can I get a post's URL and apply it into the sign up link.</p> <p>Note: The function is originally from <a href="https://wordpress.stackexchange.com/questions/274296/how-can-i-only-show-certain-posts">this question</a>.</p>
[ { "answer_id": 274651, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>You can do a conditional and return the post's URL by using a <code>get_the_permalink()</code> in conjuncti...
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274650", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123649/" ]
In WordPress, I use a function in functions.php to only not show certain posts(by category) if a user is not signed in: ``` function my_filter( $content ) { $categories = array( 'news', 'opinions', 'sports', 'other', ); if ( in_category( $categories ) ) { if ( is_logged_in() ) { return $content; } else { $content = '<p>Sorry, this post is only available to members</p> <a href="gateblogs.com/login"> Login </a>'; return $content; } } else { return $content; } } add_filter( 'the_content', 'my_filter' ); ``` I use a plugin(not important to my question), but basically, I can use something like `https://gateblogs.com/login?redirect_to=https%3A%2F%2Fgateblogs.com%2Ftechnology%2Flinux-tutorials%2Fsending-mail-from-server` to redirect to a page after a successful login. How can I get a post's URL and apply it into the sign up link. Note: The function is originally from [this question](https://wordpress.stackexchange.com/questions/274296/how-can-i-only-show-certain-posts).
I figured out how to do it with the `get_the_permalink()` function: ``` /* Protect Member Only Posts*/ function post_filter( $content ) { $categories = array( 'coding', 'python', 'linux-tutorials', 'swift', 'premium', ); if ( in_category( $categories ) ) { if ( is_user_logged_in() ) { return $content; } else { $link = get_the_permalink(); $link = str_replace(':', '%3A', $link); $link = str_replace('/', '%2F', $link); $content = "<p>Sorry, this post is only available to members. <a href=\"gateblogs.com/login?redirect_to=$link\">Sign in/Register</a></p>"; return $content; } } else { return $content; } } add_filter( 'the_content', 'post_filter' ); ``` Please note than the `str_replace` is because I has to change the link for the plugin to work.
274,659
<p>I apologize for asking such a simple question, but I am having a world of struggle in trying to convert the following echo statement to HTML with php tags inside of it. I am trying to get my custom metabox to work correctly, but it will not save my data unless I use the following format as an echo string (very frustrating).</p> <p>Thanks for any advice</p> <pre><code>echo '&lt;p&gt; &lt;label&gt; &lt;select name="horizon_sort_listb" id="horizon_sort_listb"&gt; &lt;option value="0" ' .selected($horizon_featured,'normal',false) .'&gt;Descending&lt;/option&gt; &lt;option value="special" ' .selected($horizon_featured, 'special',false) .'&gt;Ascending&lt;/option&gt; &lt;/select&gt;&lt;strong&gt;Sort Order B&lt;/strong&gt;' .'&lt;/label&gt; &lt;/p&gt;'; ?&gt; </code></pre>
[ { "answer_id": 274651, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>You can do a conditional and return the post's URL by using a <code>get_the_permalink()</code> in conjuncti...
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274659", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98671/" ]
I apologize for asking such a simple question, but I am having a world of struggle in trying to convert the following echo statement to HTML with php tags inside of it. I am trying to get my custom metabox to work correctly, but it will not save my data unless I use the following format as an echo string (very frustrating). Thanks for any advice ``` echo '<p> <label> <select name="horizon_sort_listb" id="horizon_sort_listb"> <option value="0" ' .selected($horizon_featured,'normal',false) .'>Descending</option> <option value="special" ' .selected($horizon_featured, 'special',false) .'>Ascending</option> </select><strong>Sort Order B</strong>' .'</label> </p>'; ?> ```
I figured out how to do it with the `get_the_permalink()` function: ``` /* Protect Member Only Posts*/ function post_filter( $content ) { $categories = array( 'coding', 'python', 'linux-tutorials', 'swift', 'premium', ); if ( in_category( $categories ) ) { if ( is_user_logged_in() ) { return $content; } else { $link = get_the_permalink(); $link = str_replace(':', '%3A', $link); $link = str_replace('/', '%2F', $link); $content = "<p>Sorry, this post is only available to members. <a href=\"gateblogs.com/login?redirect_to=$link\">Sign in/Register</a></p>"; return $content; } } else { return $content; } } add_filter( 'the_content', 'post_filter' ); ``` Please note than the `str_replace` is because I has to change the link for the plugin to work.
274,663
<p>I'm writing a query that switches to the main blog of a MU site using switch_to_blog(). All is well except i'm attempting to write a wp_query that includes a variable needed from the previous blog. All the content being pulled from the main blog is stored in a CPT with a taxonomy that corresponds to the various sub-blog names. I'm attempting to store bloginfo('name'); from my previous blog, and pull it into the query after switch_to_blog, but for obvious reasons, no luck (it gets the current bloginfo, not the previous.) Is there any way either to save the the previous bloginfo into a global of some sort, or to switch back to the previous blog just to get that variable mid-query? </p> <p>See my query below for better illustration:</p> <pre><code>$location = bloginfo('name'); switch_to_blog( 1 ); $the_query = new WP_Query( array( 'post_type' =&gt; 'staff', 'posts_per_page' =&gt; -1, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'location', // name of tax 'field' =&gt; 'slug', 'terms' =&gt; $location, // this doesn't work, returns nothing ), ), ) ); ?&gt; &lt;?php if ( $the_query-&gt;have_posts() ) : ?&gt; &lt;?php while ( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); ?&gt; &lt;h2&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;?php endwhile; ?&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php else : ?&gt; &lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php restore_current_blog(); ?&gt; </code></pre>
[ { "answer_id": 274651, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>You can do a conditional and return the post's URL by using a <code>get_the_permalink()</code> in conjuncti...
2017/07/25
[ "https://wordpress.stackexchange.com/questions/274663", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/16111/" ]
I'm writing a query that switches to the main blog of a MU site using switch\_to\_blog(). All is well except i'm attempting to write a wp\_query that includes a variable needed from the previous blog. All the content being pulled from the main blog is stored in a CPT with a taxonomy that corresponds to the various sub-blog names. I'm attempting to store bloginfo('name'); from my previous blog, and pull it into the query after switch\_to\_blog, but for obvious reasons, no luck (it gets the current bloginfo, not the previous.) Is there any way either to save the the previous bloginfo into a global of some sort, or to switch back to the previous blog just to get that variable mid-query? See my query below for better illustration: ``` $location = bloginfo('name'); switch_to_blog( 1 ); $the_query = new WP_Query( array( 'post_type' => 'staff', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'location', // name of tax 'field' => 'slug', 'terms' => $location, // this doesn't work, returns nothing ), ), ) ); ?> <?php if ( $the_query->have_posts() ) : ?> <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php endwhile; ?> <?php wp_reset_postdata(); ?> <?php else : ?> <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p> <?php endif; ?> <?php restore_current_blog(); ?> ```
I figured out how to do it with the `get_the_permalink()` function: ``` /* Protect Member Only Posts*/ function post_filter( $content ) { $categories = array( 'coding', 'python', 'linux-tutorials', 'swift', 'premium', ); if ( in_category( $categories ) ) { if ( is_user_logged_in() ) { return $content; } else { $link = get_the_permalink(); $link = str_replace(':', '%3A', $link); $link = str_replace('/', '%2F', $link); $content = "<p>Sorry, this post is only available to members. <a href=\"gateblogs.com/login?redirect_to=$link\">Sign in/Register</a></p>"; return $content; } } else { return $content; } } add_filter( 'the_content', 'post_filter' ); ``` Please note than the `str_replace` is because I has to change the link for the plugin to work.
274,668
<p>I have a handful of products in my WooCommerce Store set to <code>Catalog &amp; Search</code> and a bunch more just set to a visibility of just <code>Search</code>.</p> <p>I put a lot of work into making sure my Catalog was nice and clean, but now I need to do some additional work on them and am trying to retrieve the IDs of products that are ONLY in my Catalog and not just search.</p> <p>I've tried a few things, but something is amiss somewhere.</p> <p>What am I missing?</p> <pre><code>$params = array( 'posts_per_page' =&gt; -1, 'post_type' =&gt; 'product', 'orderby' =&gt; 'menu-order', 'order' =&gt; 'asc', 'fields' =&gt; 'ids', 'meta_query' =&gt; array( array( 'taxonomy' =&gt; 'product_visibility', 'value' =&gt; 'exclude-from-catalog', 'compare' =&gt; '!=') )); $wc_query = new WP_Query($params); $ids = $wc_query-&gt;posts; echo '&lt;pre&gt;'; print_r($ids); echo '&lt;/pre&gt;'; </code></pre> <p>With this Query it's still returning all Product IDs.</p> <p>I'm assuming there must be something wrong with my <code>meta_query</code> argument. What I was going for was to look for the <code>product_visibility</code> <code>taxonomy</code> and exclude (<code>!=</code>) those that have the value <code>exclude-from-catalog</code>.</p> <p>Anyone know where I'm going wrong with this?</p>
[ { "answer_id": 274651, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>You can do a conditional and return the post's URL by using a <code>get_the_permalink()</code> in conjuncti...
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274668", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/121874/" ]
I have a handful of products in my WooCommerce Store set to `Catalog & Search` and a bunch more just set to a visibility of just `Search`. I put a lot of work into making sure my Catalog was nice and clean, but now I need to do some additional work on them and am trying to retrieve the IDs of products that are ONLY in my Catalog and not just search. I've tried a few things, but something is amiss somewhere. What am I missing? ``` $params = array( 'posts_per_page' => -1, 'post_type' => 'product', 'orderby' => 'menu-order', 'order' => 'asc', 'fields' => 'ids', 'meta_query' => array( array( 'taxonomy' => 'product_visibility', 'value' => 'exclude-from-catalog', 'compare' => '!=') )); $wc_query = new WP_Query($params); $ids = $wc_query->posts; echo '<pre>'; print_r($ids); echo '</pre>'; ``` With this Query it's still returning all Product IDs. I'm assuming there must be something wrong with my `meta_query` argument. What I was going for was to look for the `product_visibility` `taxonomy` and exclude (`!=`) those that have the value `exclude-from-catalog`. Anyone know where I'm going wrong with this?
I figured out how to do it with the `get_the_permalink()` function: ``` /* Protect Member Only Posts*/ function post_filter( $content ) { $categories = array( 'coding', 'python', 'linux-tutorials', 'swift', 'premium', ); if ( in_category( $categories ) ) { if ( is_user_logged_in() ) { return $content; } else { $link = get_the_permalink(); $link = str_replace(':', '%3A', $link); $link = str_replace('/', '%2F', $link); $content = "<p>Sorry, this post is only available to members. <a href=\"gateblogs.com/login?redirect_to=$link\">Sign in/Register</a></p>"; return $content; } } else { return $content; } } add_filter( 'the_content', 'post_filter' ); ``` Please note than the `str_replace` is because I has to change the link for the plugin to work.
274,676
<p>I created a search for my site using attachments. Each attachment is in category "Pictures", so my search form looks like:</p> <pre><code>&lt;form method="get" id="searchform" action="&lt;?php bloginfo('url'); ?&gt;"&gt; &lt;input type="text" name="s" id="s" value="Search..." onfocus="if (this.value=='Search...') this.value='';" onblur="if (this.value=='') this.value='Search...';" /&gt; &lt;?php $parent = get_cat_ID("Pictures"); ?&gt; &lt;input type="hidden" name="cat" value="&lt;?php echo $parent; ?&gt;" /&gt; &lt;input type="submit" id="searchsubmit" value="" /&gt; &lt;/form&gt; </code></pre> <p>My search results page <code>search.php</code> returns those results through a <code>get_posts</code>query. The problem I am having is with the pagination. I have been able to limit the number of posts on the page and even return the pagination, but when I click on the link for the pagination, the page does not display. I am thinking because these are attachments the pages are setup a little different, but I don't know what the url looks like. My current code looks like:</p> <pre><code>&lt;?php $args = array( 'post_type' =&gt; 'attachment', 'numberposts' =&gt; '-1', 'category_name' =&gt; get_the_title() ); $images = get_posts($args); if (!empty($images)) { ?&gt; &lt;?php $limit = 5; $total = count($images); $pages = ceil($total / $limit); $result = ceil($total / $limit); $current = isset($_GET['paged']) ? $_GET['paged'] : 1; $next = $current &lt; $pages ? $current + 1 : null; $previous = $current &gt; 1 ? $current - 1 : null; $offset = ($current - 1) * $limit; $images = array_slice($images, $offset, $limit) ?&gt; &lt;h4&gt;&lt;span&gt;Search&lt;/span&gt; Results&lt;/h4&gt; &lt;ul class="category"&gt; &lt;?php foreach ($images as $image) { $title = $image-&gt;post_title; $description = $image-&gt;post_content; $attachment_link = get_attachment_link( $image-&gt;ID ); ?&gt; &lt;li&gt; &lt;div class="col1"&gt; &lt;a href="&lt;?php echo $attachment_link; ?&gt;"&gt;&lt;?php echo wp_get_attachment_image($image-&gt;ID, "medium"); ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="col2"&gt; &lt;h5&gt;&lt;?php echo $title; ?&gt;&lt;/h5&gt; &lt;p&gt;&lt;?php echo $description; ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; &lt;?php echo "&lt;p&gt;(Page: ". $current . " of " . $result .")&lt;/p&gt;"; ?&gt; &lt;? if($previous): ?&gt; &lt;a href="&lt;?php bloginfo('url'); ?&gt;?paged&lt;?= $previous ?&gt;"&gt;Previous&lt;/a&gt; &lt;? endif ?&gt; &lt;? if($next) : ?&gt; &lt;a href="&lt;?php bloginfo('url'); ?&gt;?paged&lt;?= $next ?&gt;"&gt;Next&lt;/a&gt; &lt;? endif ?&gt; &lt;?php } ?&gt; </code></pre> <p>The paging was integrated from the code I found on: <a href="https://erikeldridge.wordpress.com/2009/01/11/simple-php-paging/" rel="nofollow noreferrer">https://erikeldridge.wordpress.com/2009/01/11/simple-php-paging/</a></p> <p>I'm so close, probably just a tweak here or there, can anyone point me in the right direction?</p> <p>Thanks,<br /> Josh</p>
[ { "answer_id": 274651, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>You can do a conditional and return the post's URL by using a <code>get_the_permalink()</code> in conjuncti...
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274676", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9820/" ]
I created a search for my site using attachments. Each attachment is in category "Pictures", so my search form looks like: ``` <form method="get" id="searchform" action="<?php bloginfo('url'); ?>"> <input type="text" name="s" id="s" value="Search..." onfocus="if (this.value=='Search...') this.value='';" onblur="if (this.value=='') this.value='Search...';" /> <?php $parent = get_cat_ID("Pictures"); ?> <input type="hidden" name="cat" value="<?php echo $parent; ?>" /> <input type="submit" id="searchsubmit" value="" /> </form> ``` My search results page `search.php` returns those results through a `get_posts`query. The problem I am having is with the pagination. I have been able to limit the number of posts on the page and even return the pagination, but when I click on the link for the pagination, the page does not display. I am thinking because these are attachments the pages are setup a little different, but I don't know what the url looks like. My current code looks like: ``` <?php $args = array( 'post_type' => 'attachment', 'numberposts' => '-1', 'category_name' => get_the_title() ); $images = get_posts($args); if (!empty($images)) { ?> <?php $limit = 5; $total = count($images); $pages = ceil($total / $limit); $result = ceil($total / $limit); $current = isset($_GET['paged']) ? $_GET['paged'] : 1; $next = $current < $pages ? $current + 1 : null; $previous = $current > 1 ? $current - 1 : null; $offset = ($current - 1) * $limit; $images = array_slice($images, $offset, $limit) ?> <h4><span>Search</span> Results</h4> <ul class="category"> <?php foreach ($images as $image) { $title = $image->post_title; $description = $image->post_content; $attachment_link = get_attachment_link( $image->ID ); ?> <li> <div class="col1"> <a href="<?php echo $attachment_link; ?>"><?php echo wp_get_attachment_image($image->ID, "medium"); ?></a> </div> <div class="col2"> <h5><?php echo $title; ?></h5> <p><?php echo $description; ?></p> </div> </li> <?php } ?> </ul> <?php echo "<p>(Page: ". $current . " of " . $result .")</p>"; ?> <? if($previous): ?> <a href="<?php bloginfo('url'); ?>?paged<?= $previous ?>">Previous</a> <? endif ?> <? if($next) : ?> <a href="<?php bloginfo('url'); ?>?paged<?= $next ?>">Next</a> <? endif ?> <?php } ?> ``` The paging was integrated from the code I found on: <https://erikeldridge.wordpress.com/2009/01/11/simple-php-paging/> I'm so close, probably just a tweak here or there, can anyone point me in the right direction? Thanks, Josh
I figured out how to do it with the `get_the_permalink()` function: ``` /* Protect Member Only Posts*/ function post_filter( $content ) { $categories = array( 'coding', 'python', 'linux-tutorials', 'swift', 'premium', ); if ( in_category( $categories ) ) { if ( is_user_logged_in() ) { return $content; } else { $link = get_the_permalink(); $link = str_replace(':', '%3A', $link); $link = str_replace('/', '%2F', $link); $content = "<p>Sorry, this post is only available to members. <a href=\"gateblogs.com/login?redirect_to=$link\">Sign in/Register</a></p>"; return $content; } } else { return $content; } } add_filter( 'the_content', 'post_filter' ); ``` Please note than the `str_replace` is because I has to change the link for the plugin to work.
274,677
<p>I am trying to display a function using AJAX using a custom plugin. But doesn't seem to work.</p> <p>My Javascript</p> <pre><code>(function($) { $(document).on( 'click', 'a.mylink', function( event ) { $.ajax({ url: testing.ajax_url, data : { action : 'diplay_user_table' }, success : function( response ) { jQuery('#user_reponse').html( response ); } }) }) })(jQuery); </code></pre> <p>My PHP</p> <pre><code>add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' ); function ajax_test_enqueue_scripts() { wp_enqueue_script( 'test', plugins_url( '/test.js', __FILE__ ), array('jquery'), '1.0', true ); wp_localize_script( 'test', 'testing', array( 'ajax_url' =&gt; admin_url( 'admin-ajax.php' ) )); } add_action('wp_ajax_my_action', 'diplay_user_table'); function diplay_user_table() { echo "function is loading in div"; } </code></pre> <p>When I click on link it just displays '0'. Any ideas?</p>
[ { "answer_id": 274680, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>You're not hooking the function to wp_ajax correctly. You need to replace the <code>my_action</code> par...
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274677", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105139/" ]
I am trying to display a function using AJAX using a custom plugin. But doesn't seem to work. My Javascript ``` (function($) { $(document).on( 'click', 'a.mylink', function( event ) { $.ajax({ url: testing.ajax_url, data : { action : 'diplay_user_table' }, success : function( response ) { jQuery('#user_reponse').html( response ); } }) }) })(jQuery); ``` My PHP ``` add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' ); function ajax_test_enqueue_scripts() { wp_enqueue_script( 'test', plugins_url( '/test.js', __FILE__ ), array('jquery'), '1.0', true ); wp_localize_script( 'test', 'testing', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )); } add_action('wp_ajax_my_action', 'diplay_user_table'); function diplay_user_table() { echo "function is loading in div"; } ``` When I click on link it just displays '0'. Any ideas?
You're not hooking the function to wp\_ajax correctly. You need to replace the `my_action` part with your action name that you're using the in AJAX request. In your case it's `display_user_table`. You also need to hook it on to `wp_ajax_nopriv` so that it works for logged out users. Here's your hook with those changes: ``` add_action('wp_ajax_diplay_user_table', 'diplay_user_table'); add_action('wp_ajax_nopriv_diplay_user_table', 'diplay_user_table'); function diplay_user_table() { echo "function is loading in div"; wp_die(); } ```
274,683
<p>This is the bottom half of my child theme's functions.php.</p> <pre><code>function register_my_scripts(){ if (is_shop() || is_product_category()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } if (is_product()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/product.css'); } } add_action( 'wp_enqueue_scripts', 'register_my_scripts' ); </code></pre> <p>Why is it, when I have the following code in the same file (above it), then the style enqueues in the above code block (but below on my file) stop working, even though the 'if' block still runs (I tested with "echo 'something';" and the echo ran)?</p> <pre><code>function register_my_menu() { register_nav_menu('left-menu', __('Left Menu')); register_nav_menu('right-menu', __('Right Menu')); wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } </code></pre> <p>But when i comment out the wp_enqueue_style in the same line, so the whole file looks like:</p> <pre><code>function register_my_menu() { register_nav_menu('left-menu', __('Left Menu')); register_nav_menu('right-menu', __('Right Menu')); // wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } add_action( 'init', 'register_my_menu'); function register_my_scripts(){ // wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); if (is_shop() || is_product_category()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } if (is_product()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/product.css'); } } add_action( 'wp_enqueue_scripts', 'register_my_scripts' ); </code></pre> <p>The enqueues in <code>register_my_scripts()</code> runs properly again. </p> <p>This is a conflict that I have never seen anywhere, and why the hell doesn't WordPress throw some kind of error. It's hellish to debug these things. </p> <p>Is there a strict version of WordPress I can get somewhere, like JavaScript's "use strict"? </p> <p>The fact that they never throw any errors is sickening. </p>
[ { "answer_id": 274680, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 3, "selected": true, "text": "<p>You're not hooking the function to wp_ajax correctly. You need to replace the <code>my_action</code> par...
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274683", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124596/" ]
This is the bottom half of my child theme's functions.php. ``` function register_my_scripts(){ if (is_shop() || is_product_category()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } if (is_product()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/product.css'); } } add_action( 'wp_enqueue_scripts', 'register_my_scripts' ); ``` Why is it, when I have the following code in the same file (above it), then the style enqueues in the above code block (but below on my file) stop working, even though the 'if' block still runs (I tested with "echo 'something';" and the echo ran)? ``` function register_my_menu() { register_nav_menu('left-menu', __('Left Menu')); register_nav_menu('right-menu', __('Right Menu')); wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } ``` But when i comment out the wp\_enqueue\_style in the same line, so the whole file looks like: ``` function register_my_menu() { register_nav_menu('left-menu', __('Left Menu')); register_nav_menu('right-menu', __('Right Menu')); // wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } add_action( 'init', 'register_my_menu'); function register_my_scripts(){ // wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); if (is_shop() || is_product_category()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/shop.css'); } if (is_product()){ wp_enqueue_style( 'shop-style', get_stylesheet_directory_uri() . '/product.css'); } } add_action( 'wp_enqueue_scripts', 'register_my_scripts' ); ``` The enqueues in `register_my_scripts()` runs properly again. This is a conflict that I have never seen anywhere, and why the hell doesn't WordPress throw some kind of error. It's hellish to debug these things. Is there a strict version of WordPress I can get somewhere, like JavaScript's "use strict"? The fact that they never throw any errors is sickening.
You're not hooking the function to wp\_ajax correctly. You need to replace the `my_action` part with your action name that you're using the in AJAX request. In your case it's `display_user_table`. You also need to hook it on to `wp_ajax_nopriv` so that it works for logged out users. Here's your hook with those changes: ``` add_action('wp_ajax_diplay_user_table', 'diplay_user_table'); add_action('wp_ajax_nopriv_diplay_user_table', 'diplay_user_table'); function diplay_user_table() { echo "function is loading in div"; wp_die(); } ```
274,696
<p>I want to change the registration form of WooCommerce a little bit. I'm fine with the normal form which comes from WooCommerce but I want to add the following fields and functions:</p> <p>If a person enters the email and the password and press register, the person should be redirected to another page where the person is forced to enter the address, phone number and the full name. But how can I do that? I already googled but found nothing... Further, only if the person has entered the details, the confirmtion mail should be send. All that should also be safed with a recaptcher at the end.</p> <p>Does anybody has an idea how I can solve that? Would it be possible to redirect the person after entering the email and passwords details to a page where the person is supposed to enter the shipping details and only if those are entered the confirmtion mail gets sended?</p> <p>Kind Regards and Thank You!</p>
[ { "answer_id": 275011, "author": "dbdesigns", "author_id": 119686, "author_profile": "https://wordpress.stackexchange.com/users/119686", "pm_score": 0, "selected": false, "text": "<p>I've been trying out the same code snippet from Cloudways as well. If you don't use the snippet in functi...
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274696", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123952/" ]
I want to change the registration form of WooCommerce a little bit. I'm fine with the normal form which comes from WooCommerce but I want to add the following fields and functions: If a person enters the email and the password and press register, the person should be redirected to another page where the person is forced to enter the address, phone number and the full name. But how can I do that? I already googled but found nothing... Further, only if the person has entered the details, the confirmtion mail should be send. All that should also be safed with a recaptcher at the end. Does anybody has an idea how I can solve that? Would it be possible to redirect the person after entering the email and passwords details to a page where the person is supposed to enter the shipping details and only if those are entered the confirmtion mail gets sended? Kind Regards and Thank You!
I've been trying out the same code snippet from Cloudways as well. If you don't use the snippet in functions.php, but instead create a copy of the woocommerce file form-login.php in your child theme's folder/woocommerce/myaccount. Then the fields from the Couldways snippet can be used before the line containing: ``` <?php do_action( 'woocommerce_after_checkout_billing_form', $checkout ); ?> ```
274,701
<p>I want to modify the WooCommerce "My Account" left side navigation menu.</p> <p>For that, I have made changes in the <code>woocommerce/templates/myaccount/navigation.php</code>. The problems with this approach are:</p> <ul> <li>I can add the new items <strong>only</strong> at the first or last position in the menu. I'd need them at the 2nd and 3rd position instead....</li> <li>If WC gets updated, it could change...</li> </ul> <p>What is the best way to customize the WooCommerce "My Account" navigation menu at my convenience?</p> <p><a href="https://i.stack.imgur.com/980Bq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/980Bq.png" alt="enter image description here"></a></p>
[ { "answer_id": 277080, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 6, "selected": true, "text": "<p>For that, you do <strong>not</strong> need to modify the <a href=\"https://github.com/woocommerce/woocommerce/bl...
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274701", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124605/" ]
I want to modify the WooCommerce "My Account" left side navigation menu. For that, I have made changes in the `woocommerce/templates/myaccount/navigation.php`. The problems with this approach are: * I can add the new items **only** at the first or last position in the menu. I'd need them at the 2nd and 3rd position instead.... * If WC gets updated, it could change... What is the best way to customize the WooCommerce "My Account" navigation menu at my convenience? [![enter image description here](https://i.stack.imgur.com/980Bq.png)](https://i.stack.imgur.com/980Bq.png)
For that, you do **not** need to modify the [`woocommerce/templates/myaccount/navigation.php`](https://github.com/woocommerce/woocommerce/blob/master/templates/myaccount/navigation.php). The best way to customize the "My Account" navigation menu items is to use: * [`woocommerce_account_menu_items`](https://github.com/woocommerce/woocommerce/blob/master/includes/wc-account-functions.php#L127) filter hook to add new items to the menu. * [`array_slice()`](http://php.net/manual/fr/function.array-slice.php) to reorder them the way you want. This way, by using `woocommerce_account_menu_items` filter hook, you integrate **perfectly** your own items to WC, indeed: * Possibility to redefine your own item endpoints via the WC "Account" settings page. * WC updates automatically the item link's URL when, for example, a modification is done to the permalink settings/structure. Code example: ``` // Note the low hook priority, this should give to your other plugins the time to add their own items... add_filter( 'woocommerce_account_menu_items', 'add_my_menu_items', 99, 1 ); function add_my_menu_items( $items ) { $my_items = array( // endpoint => label '2nd-item' => __( '2nd Item', 'my_plugin' ), '3rd-item' => __( '3rd Item', 'my_plugin' ), ); $my_items = array_slice( $items, 0, 1, true ) + $my_items + array_slice( $items, 1, count( $items ), true ); return $my_items; } ``` **Note 1**: The link's url of your items is defined automatically by WC [here](https://github.com/woocommerce/woocommerce/blob/master/templates/myaccount/navigation.php#L30). To do that, WC simply append the item endpoint defined in the filter above to the "My account" page URL. So define your item endpoints accordingly. **Note 2**: In your question, it seems like you modified the WooCommerce template directly in core... `woocommerce/templates/myaccount/navigation.php` When you **have to** modify a WC template, the correct way to do it is to duplicate the template's path **relative** to the `woocommerce/templates` folder into your theme/plugin's `woocommerce` folder. For example in our case, you'd have to paste the template into: `child-theme/woocommerce/myaccount/navigation.php`.
274,719
<p>I have created my site with pure PHP-code, and now started to migrate it to Wordpress platform. Changing authentication from own system to WP-user meta was quite easy. But when i use user session data for site functions, i have to query now user meta instead of simple MySqli-queries.</p> <p>My old query is like below. Page is getting <code>$provider</code>, what is eMail-address. And with it, can fetch rest of needed values from database:</p> <pre><code>$provider=$_GET['provider']; $providername=mysqli_query($db,"SELECT name,email,phone_number,pic,province,feedback FROM $usertable WHERE email='$provider'"); while($row = mysqli_fetch_array($providername)) { $provname=$row['name']; $provemail=$row['email']; $provpic=$row['pic']; $provphone=$row['phone_number']; $provprovince=$row['province']; $feedback=$row['feedback']; } </code></pre> <p>Simple and working well. But do this same with WP-query. I tried to find solution from number of threads, but no. In my mind didn't get it as it so differently done or samples do not just fit to my need here.</p> <p>Can you help a little bit here? I think that this query can be made with WP-query as simple.</p>
[ { "answer_id": 277080, "author": "ClemC", "author_id": 73239, "author_profile": "https://wordpress.stackexchange.com/users/73239", "pm_score": 6, "selected": true, "text": "<p>For that, you do <strong>not</strong> need to modify the <a href=\"https://github.com/woocommerce/woocommerce/bl...
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274719", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124612/" ]
I have created my site with pure PHP-code, and now started to migrate it to Wordpress platform. Changing authentication from own system to WP-user meta was quite easy. But when i use user session data for site functions, i have to query now user meta instead of simple MySqli-queries. My old query is like below. Page is getting `$provider`, what is eMail-address. And with it, can fetch rest of needed values from database: ``` $provider=$_GET['provider']; $providername=mysqli_query($db,"SELECT name,email,phone_number,pic,province,feedback FROM $usertable WHERE email='$provider'"); while($row = mysqli_fetch_array($providername)) { $provname=$row['name']; $provemail=$row['email']; $provpic=$row['pic']; $provphone=$row['phone_number']; $provprovince=$row['province']; $feedback=$row['feedback']; } ``` Simple and working well. But do this same with WP-query. I tried to find solution from number of threads, but no. In my mind didn't get it as it so differently done or samples do not just fit to my need here. Can you help a little bit here? I think that this query can be made with WP-query as simple.
For that, you do **not** need to modify the [`woocommerce/templates/myaccount/navigation.php`](https://github.com/woocommerce/woocommerce/blob/master/templates/myaccount/navigation.php). The best way to customize the "My Account" navigation menu items is to use: * [`woocommerce_account_menu_items`](https://github.com/woocommerce/woocommerce/blob/master/includes/wc-account-functions.php#L127) filter hook to add new items to the menu. * [`array_slice()`](http://php.net/manual/fr/function.array-slice.php) to reorder them the way you want. This way, by using `woocommerce_account_menu_items` filter hook, you integrate **perfectly** your own items to WC, indeed: * Possibility to redefine your own item endpoints via the WC "Account" settings page. * WC updates automatically the item link's URL when, for example, a modification is done to the permalink settings/structure. Code example: ``` // Note the low hook priority, this should give to your other plugins the time to add their own items... add_filter( 'woocommerce_account_menu_items', 'add_my_menu_items', 99, 1 ); function add_my_menu_items( $items ) { $my_items = array( // endpoint => label '2nd-item' => __( '2nd Item', 'my_plugin' ), '3rd-item' => __( '3rd Item', 'my_plugin' ), ); $my_items = array_slice( $items, 0, 1, true ) + $my_items + array_slice( $items, 1, count( $items ), true ); return $my_items; } ``` **Note 1**: The link's url of your items is defined automatically by WC [here](https://github.com/woocommerce/woocommerce/blob/master/templates/myaccount/navigation.php#L30). To do that, WC simply append the item endpoint defined in the filter above to the "My account" page URL. So define your item endpoints accordingly. **Note 2**: In your question, it seems like you modified the WooCommerce template directly in core... `woocommerce/templates/myaccount/navigation.php` When you **have to** modify a WC template, the correct way to do it is to duplicate the template's path **relative** to the `woocommerce/templates` folder into your theme/plugin's `woocommerce` folder. For example in our case, you'd have to paste the template into: `child-theme/woocommerce/myaccount/navigation.php`.
274,737
<p>How to build this menu in WordPress</p> <pre><code>&lt;div class="collapse navbar-collapse" id="collapse-1"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li&gt;&lt;a href="#"&gt;our story&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;our vision&lt;/a&gt;&lt;/li&gt; &lt;li class="dropdown"&gt; &lt;a href="#"&gt;History&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;History 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;History 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;History 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>WordPress Code:</p> <pre><code>&lt;div class="collapse navbar-collapse" id="collapse-1"&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'header', 'menu_class' =&gt; 'nav navbar-nav', 'fallback_cb' =&gt; false ) ); ?&gt; &lt;/div&gt; </code></pre>
[ { "answer_id": 274743, "author": "Elidrissi simo", "author_id": 83187, "author_profile": "https://wordpress.stackexchange.com/users/83187", "pm_score": 0, "selected": false, "text": "<p>you can use Walker_Nav_Menu class if you want to modify the default wordpress menu markup.</p>\n\n<p>...
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274737", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124623/" ]
How to build this menu in WordPress ``` <div class="collapse navbar-collapse" id="collapse-1"> <ul class="nav navbar-nav"> <li><a href="#">our story</a></li> <li><a href="#">our vision</a></li> <li class="dropdown"> <a href="#">History</a> <ul class="dropdown-menu"> <li><a href="#">History 1</a></li> <li><a href="#">History 2</a></li> <li><a href="#">History 3</a></li> </ul> </li> </ul> </div> ``` WordPress Code: ``` <div class="collapse navbar-collapse" id="collapse-1"> <?php wp_nav_menu( array( 'theme_location' => 'header', 'menu_class' => 'nav navbar-nav', 'fallback_cb' => false ) ); ?> </div> ```
The easiest way to do this is to use an off-the-shelf solution. There is a WP\_Bootstrap\_Navwalker class which extends WordPress' native Walker\_Nav\_Menu class and makes your Navigation Menus ready for Bootstrap 3 or 4. [Download it from GitHub](https://github.com/wp-bootstrap/wp-bootstrap-navwalker). Add it to your theme, then add the following to the `functions.php`: ``` <?php require_once('path-to-the-directory/wp-bootstrap-navwalker.php'); ``` Change `path-to-the-directory/` to fit your needs. Next, alter your `wp_nav_menu()` with the following code: ``` <?php wp_nav_menu( array( 'menu' => 'header', // match name to yours 'theme_location' => 'header', 'container' => 'div', // no need to wrap `wp_nav_menu` manually 'container_class' => 'collapse navbar-collapse', 'container_id' => 'collapse-1', 'menu_class' => 'nav navbar-nav', 'fallback_cb' => false, 'walker' => new WP_Bootstrap_Navwalker() // Use different Walker )); ``` Note, that you don't need the `<div class="collapse navbar-collapse" id="collapse-1">` anymore as it will be added by `wp_nav_menu()` with proper CSS classes and `id`. Also, read the WP\_Bootstrap\_Navwalker README.md file carefully.
274,802
<p>Here is code , basically I want to fetch by Post author but not able to solve this any help regards this . </p> <pre><code>&lt;?php global $post; $author = get_the_author(); $args = array( 'author' =&gt;$user_ID, 'posts_per_page' =&gt; $per_page, 'author'=&gt; $author, 'post_type' =&gt; 'ultimate-auction', //'auction-status' =&gt; 'expired', 'post_status' =&gt; 'publish', 'offset' =&gt; $pagination, 'orderby' =&gt; 'meta_value', 'meta_key' =&gt; 'wdm_listing_ends', 'order' =&gt; 'DESC', ); $author_posts = new WP_Query( $args ); if( $author_posts-&gt;have_posts() ) { while( $author_posts-&gt;have_posts()) { $author_posts-&gt;the_post(); ?&gt; &lt;?php the_content();?&gt;&lt;/div&gt; &lt;?php // you should have access to any of the tags you normally // can use in The Loop } wp_reset_postdata(); } ?&gt; </code></pre>
[ { "answer_id": 274771, "author": "Rarst", "author_id": 847, "author_profile": "https://wordpress.stackexchange.com/users/847", "pm_score": 2, "selected": false, "text": "<p>Do <strong>not</strong> rely on changing plugin details to work around this issue. The code that decides a match in...
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274802", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112012/" ]
Here is code , basically I want to fetch by Post author but not able to solve this any help regards this . ``` <?php global $post; $author = get_the_author(); $args = array( 'author' =>$user_ID, 'posts_per_page' => $per_page, 'author'=> $author, 'post_type' => 'ultimate-auction', //'auction-status' => 'expired', 'post_status' => 'publish', 'offset' => $pagination, 'orderby' => 'meta_value', 'meta_key' => 'wdm_listing_ends', 'order' => 'DESC', ); $author_posts = new WP_Query( $args ); if( $author_posts->have_posts() ) { while( $author_posts->have_posts()) { $author_posts->the_post(); ?> <?php the_content();?></div> <?php // you should have access to any of the tags you normally // can use in The Loop } wp_reset_postdata(); } ?> ```
I was able to find out that wordpress does cache available updates in the wp\_options table in an option named `_site_transient_update_plugins`. By clearing this value I was able to get Wordpress to notice my changes. I used the following query: `UPDATE wp_options SET option_value='' WHERE option_name='_site_transient_update_plugins';`
274,810
<p>I'm trying to setup unit tests for a plugin I am developing. I just followed the steps at... <a href="https://make.wordpress.org/cli/handbook/plugin-unit-tests/" rel="nofollow noreferrer">https://make.wordpress.org/cli/handbook/plugin-unit-tests/</a></p> <p>However, when I run <code>phpunit</code> I get the following...</p> <pre><code>$ phpunit Installing... Running as single site... To run multisite, use -c tests/phpunit/multisite.xml Warning: Cannot modify header information - headers already sent by (output started at /private/tmp/wordpress-tests-lib/includes/bootstrap.php:68) in /Users/&lt;USERNAME&gt;/Sites/&lt;MYSITE.COM&gt;/wp-load.php on line 64 </code></pre> <p>I am running...</p> <ul> <li>Mac OS 10.12.6</li> <li>PHP v5.6.30</li> <li>PHPUnit 4.8.36</li> <li>MAMP Pro 4.2</li> </ul> <p>The error noted, <code>bootstrap.php:68</code> which is the start of the program outputting the "Installing..." text from the output noted above. Line 68 reads...</p> <pre><code>system( WP_PHP_BINARY . ' ' . escapeshellarg( dirname( __FILE__ ) . '/install.php' ) . ' ' . escapeshellarg( $config_file_path ) . ' ' . $multisite ); </code></pre>
[ { "answer_id": 274811, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>That problem sounds like your code is sending text/characters to the screen, then it sends out a page ...
2017/07/26
[ "https://wordpress.stackexchange.com/questions/274810", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28787/" ]
I'm trying to setup unit tests for a plugin I am developing. I just followed the steps at... <https://make.wordpress.org/cli/handbook/plugin-unit-tests/> However, when I run `phpunit` I get the following... ``` $ phpunit Installing... Running as single site... To run multisite, use -c tests/phpunit/multisite.xml Warning: Cannot modify header information - headers already sent by (output started at /private/tmp/wordpress-tests-lib/includes/bootstrap.php:68) in /Users/<USERNAME>/Sites/<MYSITE.COM>/wp-load.php on line 64 ``` I am running... * Mac OS 10.12.6 * PHP v5.6.30 * PHPUnit 4.8.36 * MAMP Pro 4.2 The error noted, `bootstrap.php:68` which is the start of the program outputting the "Installing..." text from the output noted above. Line 68 reads... ``` system( WP_PHP_BINARY . ' ' . escapeshellarg( dirname( __FILE__ ) . '/install.php' ) . ' ' . escapeshellarg( $config_file_path ) . ' ' . $multisite ); ```
The error is telling you that the code tried to output a HTTP response header with the `header()` function after the response body has already begun to be sent. As you noted, line 68 of `bootstrap.php` is calling that script that outputs `Installing...`. So after that output has already been sent, you can't send a response header. The next step to debug this is to find out why a response header is being sent. That isn't supposed to be happening, because here we are running the tests from the command line, we're not actually sending a page to the browser. So, we need to see where `header()` is being called. The error tells you that it is in `wp-load.php` on line 64: ``` header( 'Location: ' . $path ); ``` This line itself doesn't tell us much, but we find that it is within a big `if ... else` statement: ``` /* * If wp-config.php exists in the WordPress root, or if it exists in the root and wp-settings.php * doesn't, load wp-config.php. The secondary check for wp-settings.php has the added benefit * of avoiding cases where the current directory is a nested installation, e.g. / is WordPress(a) * and /blog/ is WordPress(b). * * If neither set of conditions is true, initiate loading the setup process. */ if ( file_exists( ABSPATH . 'wp-config.php') ) { /** The config file resides in ABSPATH */ require_once( ABSPATH . 'wp-config.php' ); } elseif ( @file_exists( dirname( ABSPATH ) . '/wp-config.php' ) && ! @file_exists( dirname( ABSPATH ) . '/wp-settings.php' ) ) { /** The config file resides one level above ABSPATH but is not part of another install */ require_once( dirname( ABSPATH ) . '/wp-config.php' ); } else { // snip header( 'Location: ' . $path ); // snip } ``` Essentially what this tells us is that `wp-load.php` is looking for the `wp-config.php` file, and isn't finding it. So it is initiating the set-up process, and as part of that it is trying to redirect to the installation page by sending the `Location` header. So you apparently have not set up your `wp-config.php` file correctly. The `wp-config.php` file was supposed to be set up by the script you ran though, so this is likely an indicator that something failed. In fact, since we are running the tests here, the `wp-tests-config.php` file is expected to be used instead. So the next step is figuring out why `wp-tests-config.php` isn't being loaded. You should be able to find that file in the `/tmp/wordpress-tests-lib/` directory.
274,816
<p>I have a featured image preview in column view in my Custom Post Types. Now I want to change the size of it. This is my code:</p> <pre><code>add_filter('manage_posts_columns', 'add_img_column'); add_filter('manage_posts_custom_column', 'manage_img_column', 10, 2); function add_img_column($columns) { $columns['img'] = 'Featured Image'; return $columns; } function manage_img_column($column_name, $post_id) { if( $column_name == 'img' ) { echo get_the_post_thumbnail($post_id, 'thumbnail'); return true; } } </code></pre> <p>And I see it like this:</p> <p><a href="https://i.stack.imgur.com/GWhh5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GWhh5.png" alt="enter image description here"></a></p> <p>So know I want to change the size of this image in this view... how... how can I get that? :)</p>
[ { "answer_id": 274817, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 2, "selected": false, "text": "<p>You can create a new size with the funcion <code>add_image_size</code>, example:</p>\n\n<p...
2017/07/27
[ "https://wordpress.stackexchange.com/questions/274816", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116847/" ]
I have a featured image preview in column view in my Custom Post Types. Now I want to change the size of it. This is my code: ``` add_filter('manage_posts_columns', 'add_img_column'); add_filter('manage_posts_custom_column', 'manage_img_column', 10, 2); function add_img_column($columns) { $columns['img'] = 'Featured Image'; return $columns; } function manage_img_column($column_name, $post_id) { if( $column_name == 'img' ) { echo get_the_post_thumbnail($post_id, 'thumbnail'); return true; } } ``` And I see it like this: [![enter image description here](https://i.stack.imgur.com/GWhh5.png)](https://i.stack.imgur.com/GWhh5.png) So know I want to change the size of this image in this view... how... how can I get that? :)
In functions.php : Make sure featured images are enabled ``` add_theme_support( 'post-thumbnails' ); ``` then add ``` add_image_size( 'thumbnail-news', '100', '75', true ); ``` And in the code above change ``` echo get_the_post_thumbnail($post_id, 'thumbnail'); ``` to ``` echo get_the_post_thumbnail($post_id, 'thumbnail-news'); ```
274,861
<p>I've written a function to get products by price range. All works, but now I need add a extra meta key, that will be like 50 - 100 and featured, but code is not returning any products. What is wrong on this code?</p> <pre><code> function product_price_filter_box($attr) { $limit = intval($attr['limit']); $min = intval($attr['min']); $max = intval($attr['max']); $query = array( 'post_status' =&gt; 'publish', 'post_type' =&gt; 'product', 'posts_per_page' =&gt; $limit, 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array( 'key' =&gt; '_price', 'value' =&gt; array($min, $max), 'compare' =&gt; 'BETWEEN', 'type' =&gt; 'NUMERIC' ), array( 'key' =&gt; 'featured', 'value' =&gt; '1', 'compare' =&gt; '=', ), ) ); $wpquery = new WP_Query($query); while ( $wpquery-&gt;have_posts() ) : $wpquery-&gt;the_post(); global $product; wc_get_template_part( 'content', 'product' ); endwhile; wp_reset_query(); } add_shortcode( 'product_price_filter_box', 'product_price_filter_box' ); </code></pre>
[ { "answer_id": 276424, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": false, "text": "<p>The featured product's meta key is <code>_featured</code>, but you are using <code>featured</code> in your ...
2017/07/27
[ "https://wordpress.stackexchange.com/questions/274861", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44844/" ]
I've written a function to get products by price range. All works, but now I need add a extra meta key, that will be like 50 - 100 and featured, but code is not returning any products. What is wrong on this code? ``` function product_price_filter_box($attr) { $limit = intval($attr['limit']); $min = intval($attr['min']); $max = intval($attr['max']); $query = array( 'post_status' => 'publish', 'post_type' => 'product', 'posts_per_page' => $limit, 'meta_query' => array( 'relation' => 'AND', array( 'key' => '_price', 'value' => array($min, $max), 'compare' => 'BETWEEN', 'type' => 'NUMERIC' ), array( 'key' => 'featured', 'value' => '1', 'compare' => '=', ), ) ); $wpquery = new WP_Query($query); while ( $wpquery->have_posts() ) : $wpquery->the_post(); global $product; wc_get_template_part( 'content', 'product' ); endwhile; wp_reset_query(); } add_shortcode( 'product_price_filter_box', 'product_price_filter_box' ); ```
The featured product's meta key is `_featured`, but you are using `featured` in your meta query. This will return no products, since the key doesn't exist. Also, as far as I know, the value of the key is `yes`, so your arguments should be like this: ``` array( 'key' => '_featured', 'value' => 'yes', ) ``` Another note, is to use the proper way to get the shortcode's attribute. You can do so by using `shortcode_atts()` function. Here is the syntax for your case: ``` $atts = shortcode_atts( array( 'limit' => '20', 'min' => '1' 'max' => '2' ), $atts, 'product_price_filter_box' ); $limit = intval($atts['limit']); $min = intval($atts['min']); $max = intval($atts['max']); ``` You might want to limit the maximum posts a user can get. This can be done by using the `min()` function: ``` $limit = min(20, $limit); ``` And a final note. If you are using `WP_Query`, you should use `wp_reset_postdata();` instead of `wp_reset_query();`, which is used after you use `query_posts();`.
274,864
<p>How can I load Google font only if custom logo is not uploaded?</p> <p>I know how to load resource if we are on this or that page, but not sure how to do this?</p>
[ { "answer_id": 274865, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 1, "selected": false, "text": "<p>The code is not tested but is a good starting point, you may need to add action to enqueue the css or y...
2017/07/27
[ "https://wordpress.stackexchange.com/questions/274864", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/66784/" ]
How can I load Google font only if custom logo is not uploaded? I know how to load resource if we are on this or that page, but not sure how to do this?
There is a function for this purpose, called [`has_custom_logo()`](https://developer.wordpress.org/reference/functions/has_custom_logo/). You can check whether the website has a custom logo or not by having this conditional: ``` if ( ! has_custom_logo() ) { // Enqueue some google fonts wp_enqueue_style( 'google-fonts', 'https://fonts.googleapis.com/css?family=Roboto:400' ); } ```
274,885
<p>It would be a right way to enqueue the scripts using foreach loop only for <code>jquery</code>, <code>jquery-ui-widge</code>t, <code>jquery-UI-accordion</code>, <code>jquery-ui-slider</code>, <code>jquery-ui-tabs</code>, <code>jquery-ui-datepicker</code>, <code>Jquery-ui-dialog</code> and <code>Jquery-ui-button</code> because I have to write it many times so </p> <p>I have make it like this:</p> <pre><code> $jquery_ui = array( 'jquery', 'jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-accordion', 'jquery-ui-slider', 'jquery-ui-tabs', 'jquery-ui-datepicker', 'jquery-ui-dialog', 'jquery-ui-button', ); // Framework JS foreach ($jquery_ui as $ui) { wp_enqueue_script($ui); } </code></pre> <p>So I just want to know this laziness is a right way or not:)</p>
[ { "answer_id": 274887, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>Yes you can. But to make sure the script has not already been registered or enqueued, use <a href=\"https://...
2017/07/27
[ "https://wordpress.stackexchange.com/questions/274885", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/108146/" ]
It would be a right way to enqueue the scripts using foreach loop only for `jquery`, `jquery-ui-widge`t, `jquery-UI-accordion`, `jquery-ui-slider`, `jquery-ui-tabs`, `jquery-ui-datepicker`, `Jquery-ui-dialog` and `Jquery-ui-button` because I have to write it many times so I have make it like this: ``` $jquery_ui = array( 'jquery', 'jquery-ui-core', 'jquery-ui-widget', 'jquery-ui-accordion', 'jquery-ui-slider', 'jquery-ui-tabs', 'jquery-ui-datepicker', 'jquery-ui-dialog', 'jquery-ui-button', ); // Framework JS foreach ($jquery_ui as $ui) { wp_enqueue_script($ui); } ``` So I just want to know this laziness is a right way or not:)
Yes you can. But to make sure the script has not already been registered or enqueued, use [`wp_script_is()`](https://codex.wordpress.org/Function_Reference/wp_script_is) as follows: ``` foreach( $jquery_ui as $ui ) { if( !wp_script_is( $ui ) ) { wp_enqueue_script( $ui ); } } ``` This will prevent conflicts due to another instance of the script being already enqueued.
274,908
<p>I have a wordpress site on main.com and a second one on blog.main.com</p> <p>main.com already had an ssl certificate working.</p> <p>In cPanel I installed a new wildcard ssl certificate intended for '*.main.com'</p> <p>(sorry, apparently i don't have enough reputation to post more than 2 links)</p> <p>At this point: https main.com was continuing to function properly.</p> <p>http blog.main.com was still working.</p> <p>https blog.main.com was redirecting to https main.com</p> <p>So the blog needs more work. </p> <p>I changed the wordpress site-url and site-address of the blog to '<a href="https://blog.main.com" rel="nofollow noreferrer">https://blog.main.com</a>'.</p> <p>And I changed the .htaccess of the blog and added 3 lines on top:</p> <pre><code>RewriteEngine on RewriteCond %{HTTPS} !=on [NC] RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>Now: https blog.main.com still redirects to https main.com.</p> <p>http blog.main.com also redirects to https main.com.</p> <p>(Changing the site-url and address and the .htaccess back, doesn't reverse the redirect.)</p> <p>The only redirect in cPanel is 403 for '.(htaccess|htpasswd|errordocs|logs)$'</p> <p>edit: Note that mail.main.com is also redirecting the main.com.</p> <p>What could be causing the blog to redirect to the main site.</p>
[ { "answer_id": 274887, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 2, "selected": true, "text": "<p>Yes you can. But to make sure the script has not already been registered or enqueued, use <a href=\"https://...
2017/07/27
[ "https://wordpress.stackexchange.com/questions/274908", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124714/" ]
I have a wordpress site on main.com and a second one on blog.main.com main.com already had an ssl certificate working. In cPanel I installed a new wildcard ssl certificate intended for '\*.main.com' (sorry, apparently i don't have enough reputation to post more than 2 links) At this point: https main.com was continuing to function properly. http blog.main.com was still working. https blog.main.com was redirecting to https main.com So the blog needs more work. I changed the wordpress site-url and site-address of the blog to '<https://blog.main.com>'. And I changed the .htaccess of the blog and added 3 lines on top: ``` RewriteEngine on RewriteCond %{HTTPS} !=on [NC] RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L] # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress ``` Now: https blog.main.com still redirects to https main.com. http blog.main.com also redirects to https main.com. (Changing the site-url and address and the .htaccess back, doesn't reverse the redirect.) The only redirect in cPanel is 403 for '.(htaccess|htpasswd|errordocs|logs)$' edit: Note that mail.main.com is also redirecting the main.com. What could be causing the blog to redirect to the main site.
Yes you can. But to make sure the script has not already been registered or enqueued, use [`wp_script_is()`](https://codex.wordpress.org/Function_Reference/wp_script_is) as follows: ``` foreach( $jquery_ui as $ui ) { if( !wp_script_is( $ui ) ) { wp_enqueue_script( $ui ); } } ``` This will prevent conflicts due to another instance of the script being already enqueued.
274,941
<p>Is there a way to set an alias on the meta_query arguments when running a <code>get_posts()</code>? One of my queries is performing poorly. To optimize I just need to be able to reuse the same joined table instead of joining in 3 tables when only one is needed.</p> <p>My current example...</p> <pre><code>$args = array( 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array( 'key' =&gt; 'abc_type', 'value' =&gt; array('puppy', 'kitten'), 'compare' =&gt; 'IN', ), array( 'relation' =&gt; 'OR', array( 'relation' =&gt; 'AND', array( 'key' =&gt; 'abc_type', 'value' =&gt; 'puppy', 'compare' =&gt; '=', ), array( 'key' =&gt; 'abc_color', 'value' =&gt; 'pink', 'compare' =&gt; '=', ), ), array( 'relation' =&gt; 'AND', array( 'key' =&gt; 'abc_type', 'value' =&gt; 'kitten', 'compare' =&gt; '=', ), array( 'key' =&gt; 'abc_size', 'value' =&gt; 'large', 'compare' =&gt; '=', ), ), ), ) ); get_posts($args); </code></pre> <p>which basically translates to this in straight SQL...</p> <pre class="lang-sql prettyprint-override"><code>SELECT posts.* FROM posts INNER JOIN postmeta ON ( posts.ID = postmeta.post_id ) INNER JOIN postmeta AS mt1 ON ( posts.ID = mt1.post_id ) INNER JOIN postmeta AS mt2 ON ( posts.ID = mt2.post_id ) INNER JOIN postmeta AS mt3 ON ( posts.ID = mt3.post_id ) WHERE 1=1 AND ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value IN ('puppy','kitten') ) AND ( ( ( mt1.meta_key = 'abc_type' AND mt1.meta_value = 'puppy' ) AND ( mt2.meta_key = 'abc_color' AND mt2.meta_value &gt; 'pink' ) ) OR ( ( mt3.meta_key = 'abc_type' AND mt3.meta_value = 'kitten' ) AND ( mt4.meta_key = 'abc_size' AND mt4.meta_value = 'large' ) ) ) ) AND posts.post_type = 'abc_mypost' AND ((posts.post_status = 'publish')) GROUP BY posts.ID ORDER BY posts.post_title ASC; </code></pre> <p>However, this is adding 2 extra joins for the custom meta field <code>abc_type</code> and as such performance has taken a big hit. Is there a way to be able to reference the same alias for multiple meta_query arguments? Basically, <code>mt1</code> and <code>mt3</code> are totally unnecessary, I should just be able to reference the first <code>postmeta</code> table that is used with the first <code>( postmeta.meta_key = 'abc_type' AND postmeta.meta_value IN ('puppy','kitten') )</code>. Or at least if I can set a custom alias on each of these I could reference that.</p> <p>A more optimal query would be...</p> <pre class="lang-sql prettyprint-override"><code>SELECT posts.* FROM posts INNER JOIN postmeta ON ( posts.ID = postmeta.post_id ) INNER JOIN postmeta AS mt1 ON ( posts.ID = mt1.post_id ) INNER JOIN postmeta AS mt2 ON ( posts.ID = mt2.post_id ) WHERE 1=1 AND ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value IN ('puppy','kitten') ) AND ( ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'puppy' ) AND ( mt1.meta_key = 'abc_color' AND mt1.meta_value &gt; 'pink' ) ) OR ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'kitten' ) AND ( mt2.meta_key = 'abc_color' AND mt2.meta_value = 'green' ) ) ) ) AND posts.post_type = 'abc_mypost' AND ((posts.post_status = 'publish')) GROUP BY posts.ID ORDER BY posts.post_title ASC; </code></pre> <p>Thoughts?</p>
[ { "answer_id": 274944, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": -1, "selected": false, "text": "<p>I'm not really a database guy, but I played one on TV once...</p>\n\n<p>Wouldn't this part</p>\n\n<pr...
2017/07/27
[ "https://wordpress.stackexchange.com/questions/274941", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/28787/" ]
Is there a way to set an alias on the meta\_query arguments when running a `get_posts()`? One of my queries is performing poorly. To optimize I just need to be able to reuse the same joined table instead of joining in 3 tables when only one is needed. My current example... ``` $args = array( 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'abc_type', 'value' => array('puppy', 'kitten'), 'compare' => 'IN', ), array( 'relation' => 'OR', array( 'relation' => 'AND', array( 'key' => 'abc_type', 'value' => 'puppy', 'compare' => '=', ), array( 'key' => 'abc_color', 'value' => 'pink', 'compare' => '=', ), ), array( 'relation' => 'AND', array( 'key' => 'abc_type', 'value' => 'kitten', 'compare' => '=', ), array( 'key' => 'abc_size', 'value' => 'large', 'compare' => '=', ), ), ), ) ); get_posts($args); ``` which basically translates to this in straight SQL... ```sql SELECT posts.* FROM posts INNER JOIN postmeta ON ( posts.ID = postmeta.post_id ) INNER JOIN postmeta AS mt1 ON ( posts.ID = mt1.post_id ) INNER JOIN postmeta AS mt2 ON ( posts.ID = mt2.post_id ) INNER JOIN postmeta AS mt3 ON ( posts.ID = mt3.post_id ) WHERE 1=1 AND ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value IN ('puppy','kitten') ) AND ( ( ( mt1.meta_key = 'abc_type' AND mt1.meta_value = 'puppy' ) AND ( mt2.meta_key = 'abc_color' AND mt2.meta_value > 'pink' ) ) OR ( ( mt3.meta_key = 'abc_type' AND mt3.meta_value = 'kitten' ) AND ( mt4.meta_key = 'abc_size' AND mt4.meta_value = 'large' ) ) ) ) AND posts.post_type = 'abc_mypost' AND ((posts.post_status = 'publish')) GROUP BY posts.ID ORDER BY posts.post_title ASC; ``` However, this is adding 2 extra joins for the custom meta field `abc_type` and as such performance has taken a big hit. Is there a way to be able to reference the same alias for multiple meta\_query arguments? Basically, `mt1` and `mt3` are totally unnecessary, I should just be able to reference the first `postmeta` table that is used with the first `( postmeta.meta_key = 'abc_type' AND postmeta.meta_value IN ('puppy','kitten') )`. Or at least if I can set a custom alias on each of these I could reference that. A more optimal query would be... ```sql SELECT posts.* FROM posts INNER JOIN postmeta ON ( posts.ID = postmeta.post_id ) INNER JOIN postmeta AS mt1 ON ( posts.ID = mt1.post_id ) INNER JOIN postmeta AS mt2 ON ( posts.ID = mt2.post_id ) WHERE 1=1 AND ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value IN ('puppy','kitten') ) AND ( ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'puppy' ) AND ( mt1.meta_key = 'abc_color' AND mt1.meta_value > 'pink' ) ) OR ( ( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'kitten' ) AND ( mt2.meta_key = 'abc_color' AND mt2.meta_value = 'green' ) ) ) ) AND posts.post_type = 'abc_mypost' AND ((posts.post_status = 'publish')) GROUP BY posts.ID ORDER BY posts.post_title ASC; ``` Thoughts?
You can use the `posts_where` and `posts_join` filters to modify the query. It's not very elegant, but you should be able to mess with these two filters so that your sql is more optimized. It's kind of brute-forcey, but I can't see a better way in the WP\_Query class. That's not saying there isn't though. ``` //* Make sure to not suppress filters $args = array( 'suppress_filters' => false, //* rest of args unchanged ); add_filter( 'posts_where', function( $sql ) { $sql = str_replace( "( mt1.meta_key = 'abc_type' AND mt1.meta_value = 'puppy' )", "( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'puppy' )", $sql ); $sql = str_replace( "( mt3.meta_key = 'abc_type' AND mt3.meta_value = 'kitten' )", "( postmeta.meta_key = 'abc_type' AND postmeta.meta_value = 'kitten' )", $sql ); $sql = str_replace( [ 'mt2', 'mt4' ], [ 'mt1', 'mt2' ], $sql ); return $sql; }); add_filter( 'posts_join', function( $sql ) { $sql = str_replace( " INNER JOIN wp_postmeta AS mt4 ON ( wp_posts.ID = mt4.post_id )", "", $sql ); $sql = str_replace( " INNER JOIN wp_postmeta AS mt3 ON ( wp_posts.ID = mt3.post_id )", "", $sql ); return $sql; }); ``` There should probably be some checks in there so that you're not accidentally modifying other queries. That's left as an exercise for the reader.
274,947
<p>The AdWords Documentation on how to <a href="https://support.google.com/adwords/answer/6095947?hl=en" rel="nofollow noreferrer">Track transaction-specific conversion values</a> states a PHP code as such:</p> <pre><code>&lt;!-- Google Code for Purchase Conversion Page --&gt; &lt;script type="text/javascript"&gt; /* &lt;![CDATA[ */ var google_conversion_id = 1234567890; var google_conversion_language = "en"; var google_conversion_format = "1"; var google_conversion_color = "666666"; var google_conversion_label = "xxxxXXx1xXXX123X1xX"; if (&lt;? echo $totalValue ?&gt;) { var google_conversion_value = &lt;? echo $totalValue ?&gt;; var google_conversion_currency = &lt;? echo $currency ?&gt;; } var google_remarketing_only = false; /* ]]&gt; */ &lt;/script&gt; &lt;script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"&gt; &lt;/script&gt; &lt;noscript&gt; &lt;div style="display:inline;"&gt; &lt;img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/ conversion/1234567890/?value= &lt;? echo $totalValue ?&gt;&amp;amp;currency_code=&lt;? echo $currency ?&gt; &amp;amp;label=xxxxXXx1xXXX123X1xX&amp;amp;guid=ON&amp;amp;script=0"&gt; &lt;/div&gt; &lt;/noscript&gt; &lt;/body&gt; </code></pre> <p>This indicates to me two things:</p> <ol> <li>We need to put the total order value in a <code>$totalValue</code> variable and the currency value into <code>$currency</code>.</li> <li>It should be placed at the end of the <code>&lt;/body&gt;</code> on the page.</li> </ol> <p>Aside from creating your own custom 'Thank You' page on Order Completion and adding it where you want in a custom page template, what's the best way to hook onto the default 'Thank You' page?</p> <p>The WooCommerce Documentation has something on <a href="https://docs.woocommerce.com/document/custom-tracking-code-for-the-thanks-page/" rel="nofollow noreferrer">Custom tracking code for the thanks page</a> that just simply hooks onto <code>woocommerce_thankyou</code>. Minified it looks like:</p> <pre><code>add_action( 'woocommerce_thankyou', 'my_custom_tracking' ); function my_custom_tracking( $order_id ) { // Lets grab the order $order = wc_get_order( $order_id ); // Do whatever else } </code></pre> <p>But doesn't mention AdWords specifically.</p> <p>I know through my own testing, that once we define <code>$order = wc_get_order( $order_id );</code> we can get our variables simply using:</p> <pre><code>$totalValue = $order-&gt;get_total(); $currency = $order-&gt;currency; </code></pre> <p>This would bring about a complete function like so:</p> <pre><code>add_action( 'woocommerce_thankyou', 'my_custom_tracking' ); function my_custom_tracking( $order_id ) { $order = wc_get_order( $order_id ); $totalValue = $order-&gt;get_total(); $currency = $order-&gt;currency; ?&gt; &lt;!-- Google Code for Purchase Conversion Page --&gt; &lt;script type="text/javascript"&gt; /* &lt;![CDATA[ */ var google_conversion_id = 1234567890; var google_conversion_language = "en"; var google_conversion_format = "1"; var google_conversion_color = "666666"; var google_conversion_label = "xxxxXXx1xXXX123X1xX"; if (&lt;?php echo $totalValue ?&gt;) { var google_conversion_value = &lt;?php echo $totalValue ?&gt;; var google_conversion_currency = &lt;?php echo $currency ?&gt;; } var google_remarketing_only = false; /* ]]&gt; */ &lt;/script&gt; &lt;script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"&gt; &lt;/script&gt; &lt;noscript&gt; &lt;div style="display:inline;"&gt; &lt;img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/ conversion/1234567890/?value= &lt;?php echo $totalValue ?&gt;&amp;amp;currency_code=&lt;?php echo $currency ?&gt; &amp;amp;label=xxxxXXx1xXXX123X1xX&amp;amp;guid=ON&amp;amp;script=0"&gt; &lt;/div&gt; &lt;/noscript&gt; &lt;?php } </code></pre> <p>But does not allow us to put it at the end of the <code>&lt;/body&gt;</code> as the AdWords Documentation states.</p> <p>I can't find any information on Transaction Specific values like this in WooCommerce for AdWords, at least nothing definite. There are plenty of plug-ins but they all seem a bit overkill (correct me if I'm wrong) if it's as simple as adding a function perhaps such as the one above.</p> <p>My Questions Are:</p> <ul> <li>Would the above function work just fine regardless?</li> <li>Is there anyway to place the function directly directly above the <code>&lt;/body&gt;</code> as Google suggests?</li> <li>Is there anything else I might be missing here for a proper configuration?</li> </ul>
[ { "answer_id": 274955, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 1, "selected": false, "text": "<p>From the documentation you cited for AdWords: \"When inserting the tag, you'll place it on the static port...
2017/07/28
[ "https://wordpress.stackexchange.com/questions/274947", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/102212/" ]
The AdWords Documentation on how to [Track transaction-specific conversion values](https://support.google.com/adwords/answer/6095947?hl=en) states a PHP code as such: ``` <!-- Google Code for Purchase Conversion Page --> <script type="text/javascript"> /* <![CDATA[ */ var google_conversion_id = 1234567890; var google_conversion_language = "en"; var google_conversion_format = "1"; var google_conversion_color = "666666"; var google_conversion_label = "xxxxXXx1xXXX123X1xX"; if (<? echo $totalValue ?>) { var google_conversion_value = <? echo $totalValue ?>; var google_conversion_currency = <? echo $currency ?>; } var google_remarketing_only = false; /* ]]> */ </script> <script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"> </script> <noscript> <div style="display:inline;"> <img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/ conversion/1234567890/?value= <? echo $totalValue ?>&amp;currency_code=<? echo $currency ?> &amp;label=xxxxXXx1xXXX123X1xX&amp;guid=ON&amp;script=0"> </div> </noscript> </body> ``` This indicates to me two things: 1. We need to put the total order value in a `$totalValue` variable and the currency value into `$currency`. 2. It should be placed at the end of the `</body>` on the page. Aside from creating your own custom 'Thank You' page on Order Completion and adding it where you want in a custom page template, what's the best way to hook onto the default 'Thank You' page? The WooCommerce Documentation has something on [Custom tracking code for the thanks page](https://docs.woocommerce.com/document/custom-tracking-code-for-the-thanks-page/) that just simply hooks onto `woocommerce_thankyou`. Minified it looks like: ``` add_action( 'woocommerce_thankyou', 'my_custom_tracking' ); function my_custom_tracking( $order_id ) { // Lets grab the order $order = wc_get_order( $order_id ); // Do whatever else } ``` But doesn't mention AdWords specifically. I know through my own testing, that once we define `$order = wc_get_order( $order_id );` we can get our variables simply using: ``` $totalValue = $order->get_total(); $currency = $order->currency; ``` This would bring about a complete function like so: ``` add_action( 'woocommerce_thankyou', 'my_custom_tracking' ); function my_custom_tracking( $order_id ) { $order = wc_get_order( $order_id ); $totalValue = $order->get_total(); $currency = $order->currency; ?> <!-- Google Code for Purchase Conversion Page --> <script type="text/javascript"> /* <![CDATA[ */ var google_conversion_id = 1234567890; var google_conversion_language = "en"; var google_conversion_format = "1"; var google_conversion_color = "666666"; var google_conversion_label = "xxxxXXx1xXXX123X1xX"; if (<?php echo $totalValue ?>) { var google_conversion_value = <?php echo $totalValue ?>; var google_conversion_currency = <?php echo $currency ?>; } var google_remarketing_only = false; /* ]]> */ </script> <script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"> </script> <noscript> <div style="display:inline;"> <img height="1" width="1" style="border-style:none;" alt="" src="//www.googleadservices.com/pagead/ conversion/1234567890/?value= <?php echo $totalValue ?>&amp;currency_code=<?php echo $currency ?> &amp;label=xxxxXXx1xXXX123X1xX&amp;guid=ON&amp;script=0"> </div> </noscript> <?php } ``` But does not allow us to put it at the end of the `</body>` as the AdWords Documentation states. I can't find any information on Transaction Specific values like this in WooCommerce for AdWords, at least nothing definite. There are plenty of plug-ins but they all seem a bit overkill (correct me if I'm wrong) if it's as simple as adding a function perhaps such as the one above. My Questions Are: * Would the above function work just fine regardless? * Is there anyway to place the function directly directly above the `</body>` as Google suggests? * Is there anything else I might be missing here for a proper configuration?
As the developer of the [WooCommerce AdWords Conversion Tracking](https://wordpress.org/plugins/woocommerce-google-adwords-conversion-tracking-tag/) plugin I can give you a few answers to your questions plus some reasons to use a plugin or ours in particular. Answers to your questions: 1. Your function probably will be impaired or not working at all. The reason is, that WordPress filters out the CDATA tags automatically (everything within the content part that is between `<body></body>`). And you can't do anything about it. The filter can't be turned off. It is a bug that has been reported long time ago: <http://core.trac.wordpress.org/ticket/3670> There is an experimental workaround, but it likely will not work with all themes. 2. In theory yes. But Googles instruction is more of a recommendation. The tag will work regardless. If you put it in the header, or footer or directly after the tag, it doesn't really matter. And it is a quite difficult task to position it so exactly using WordPress if you don't want to edit your theme template files. 3. Yes. You are missing: Deduplication, suppression of tracking for failed payments, tax and shipment exclusion, avoid tracking of admins and shop managers to start with. Deduplication: If the visitor reloads the thankyou page for whatever reason, the order will be tracked twice (or even more times). Failed payments: If a payment fails the thankyou page will still be triggered and thus your tracking code. Tax and shipment: Generally you don't want to track shipment and tax, just the product price. To get the value without tax and shipment you'll have to use get\_subtotal(). In our plugin we have solutions for all issues mentioned above. And we are working on even more interesting functions. In general plugins can be a good thing if they go beyond just including simple functions, use best practices to avoid performance drag and keep the installations safe.
274,948
<p>WordPress Devs. I am new to WordPress and Web development. So far WordPress Rest API v2 works well. I was writing a custom API/route/endpoint for my project using the following function. </p> <pre><code> get_post($postId); </code></pre> <p>Here the keys that are return as a response are mainly <em>ID, post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt, post_status, comment_status.</em></p> <p>However, the keys obtain from <a href="http://techdevfan.com/wp-json/wp/v2/posts" rel="nofollow noreferrer">http://techdevfan.com/wp-json/wp/v2/posts</a> are different from the custom API post object mainly <em>id date, date_gmt, guid, modified, status, link, title.</em></p> <p>There is completely no problem in serializing both the response. I just want to know is there any alternative to such problem so that there is no ambiguity in the keys for the two cases other than renaming the keys in $post object of a custom endpoint. </p>
[ { "answer_id": 274955, "author": "Tim Elsass", "author_id": 80375, "author_profile": "https://wordpress.stackexchange.com/users/80375", "pm_score": 1, "selected": false, "text": "<p>From the documentation you cited for AdWords: \"When inserting the tag, you'll place it on the static port...
2017/07/28
[ "https://wordpress.stackexchange.com/questions/274948", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125779/" ]
WordPress Devs. I am new to WordPress and Web development. So far WordPress Rest API v2 works well. I was writing a custom API/route/endpoint for my project using the following function. ``` get_post($postId); ``` Here the keys that are return as a response are mainly *ID, post\_author, post\_date, post\_date\_gmt, post\_content, post\_title, post\_excerpt, post\_status, comment\_status.* However, the keys obtain from <http://techdevfan.com/wp-json/wp/v2/posts> are different from the custom API post object mainly *id date, date\_gmt, guid, modified, status, link, title.* There is completely no problem in serializing both the response. I just want to know is there any alternative to such problem so that there is no ambiguity in the keys for the two cases other than renaming the keys in $post object of a custom endpoint.
As the developer of the [WooCommerce AdWords Conversion Tracking](https://wordpress.org/plugins/woocommerce-google-adwords-conversion-tracking-tag/) plugin I can give you a few answers to your questions plus some reasons to use a plugin or ours in particular. Answers to your questions: 1. Your function probably will be impaired or not working at all. The reason is, that WordPress filters out the CDATA tags automatically (everything within the content part that is between `<body></body>`). And you can't do anything about it. The filter can't be turned off. It is a bug that has been reported long time ago: <http://core.trac.wordpress.org/ticket/3670> There is an experimental workaround, but it likely will not work with all themes. 2. In theory yes. But Googles instruction is more of a recommendation. The tag will work regardless. If you put it in the header, or footer or directly after the tag, it doesn't really matter. And it is a quite difficult task to position it so exactly using WordPress if you don't want to edit your theme template files. 3. Yes. You are missing: Deduplication, suppression of tracking for failed payments, tax and shipment exclusion, avoid tracking of admins and shop managers to start with. Deduplication: If the visitor reloads the thankyou page for whatever reason, the order will be tracked twice (or even more times). Failed payments: If a payment fails the thankyou page will still be triggered and thus your tracking code. Tax and shipment: Generally you don't want to track shipment and tax, just the product price. To get the value without tax and shipment you'll have to use get\_subtotal(). In our plugin we have solutions for all issues mentioned above. And we are working on even more interesting functions. In general plugins can be a good thing if they go beyond just including simple functions, use best practices to avoid performance drag and keep the installations safe.
274,984
<p>Wordpress by default already handles the routes to the requested pages but beeing a starter in react and wanting to learn more about it i've found out that you need to create all of your routes. This will extend the app development alot.. What's currently beeing used to overcome this problem?</p>
[ { "answer_id": 275014, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 0, "selected": false, "text": "<p>You basically have to do it yourself. The REST API is only responsible for returning the data, the fron...
2017/07/28
[ "https://wordpress.stackexchange.com/questions/274984", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107897/" ]
Wordpress by default already handles the routes to the requested pages but beeing a starter in react and wanting to learn more about it i've found out that you need to create all of your routes. This will extend the app development alot.. What's currently beeing used to overcome this problem?
You will need to add `react-router-dom` with `npm` or `yarn`. Once you add those, you will need to import some modules into your React app. You will need `BrowserRouter`, `Route`, `NavLink`, & `withRouter`. `BrowserRouter` is to be on the outmost parent Component that manages the history API. Ideally, you would just put your `<App />` component inside it in your `index.js` file, but I think it's simpler to not include 3 separate files in my comment and just wrapped my `<App />` response in it here instead. Any component inside `BrowserRouter` can use `<Route />` and `<NavLink />`. `Route` will trigger based on the request URL and you change the request URL either by manually typing an address or using a `<NavLink />` component. At the bottom of the Dropdown component you will see I export the component inside `withRouter`. This adds useful information to the component's props such as the current url slug. Here is a simple example. `yarn add react-router-dom` ``` // App.js import React, {Component} from 'react'; import { BrowserRouter, Route } from 'react-router-dom'; import axios from 'axios'; import './App.scss'; import {wpAPI} from '../../data/api'; import FrontPage from '../../templates/FrontPage'; import Header from '../Header/Header'; import Post from '../Post/Post'; import Sidebar from '../Sidebar/Sidebar'; import Footer from '../Footer/Footer'; import Spinner from '../Spinner/Spinner'; // Create a React Component class App extends Component { state = { pages: [], posts: [], postTypes: [], acf: [], events: [], }; componentDidMount() { var keys = Object.keys(this.state); for ( var i = 0; i < keys.length; i++){ this.getPosts(keys[i]); } } renderContent() { if ( this.state.pages ) { const {pages} = this.state; return ( // Outermost element, contains single root child element. <BrowserRouter> <section id="app" className="animated fadeIn"> <Header /> <main> // Path = Url after domain & protocal // Use render prop to pass props to component, else use component prop ex. component={FrontPage} <Route path="/" exact render={(props) => <FrontPage {...props} pages={ pages } /> } /> <Route path="/about" exact render={(props) => <Post {...props} post={ this.state.pages[3] } /> } /> </main> <Sidebar /> <Footer /> </section> </BrowserRouter> ) } return <Spinner message='loading...' />; } render() { return this.renderContent(); } /** * Takes a post type, builds post type as array of post json in state * * @param {[string]} type [Post Type] */ getPosts = async (type) => { const response = await axios.get(wpAPI[type]); this.setState({[type]: response.data}) } }; export default App; ``` . ``` // Menu.js import React, {Component} from 'react'; import { library } from '@fortawesome/fontawesome-svg-core'; import { faChevronDown, faChevronUp } from "@fortawesome/free-solid-svg-icons"; import { NavLink, withRouter } from 'react-router-dom'; import './Dropdown.scss'; library.add(faChevronDown, faChevronUp); class Dropdown extends Component { constructor(props){ super(props) const {title, list, to} = props; this.state = { listOpen: false, title: title, list: list, to: to, }; // console.log(this.state); } handleClickOutside(){ this.setState({ listOpen: false }) } toggleList(){ this.setState(prevState => ({ listOpen: !prevState.listOpen })) } render() { const {listOpen, title, list, to} = this.state; if ( list ) { return( <div className="dropdown dropdown__wrapper"> <header className="dropdown__header" onClick={() => this.toggleList()}> <div className="dropdown__title">{title}</div> {listOpen ? <i className="fas fa-chevron-up"></i> : <i className="fas fa-chevron-down"></i> } </header> {listOpen && <ul className="dropdown__list"> {list.map((item) => ( <NavLink className="dropdown__item" key={item.id} to={item.to}>{item.title}</NavLink> ))} </ul>} </div> ); } return( <div className="dropdown dropdown__wrapper"> <div className="dropdown__header" onClick={() => this.toggleList()}> <NavLink className="dropdown__title" to={to}>{title}</NavLink> </div> </div> ); } } export default withRouter(Dropdown); ```
274,986
<p>I needed to translate strings on another language than the current $locale, so I need to change the locale and restore it later, and I really couldn't repeat all the code for the 30++ strings I had to translate.</p> <p>So I ended up with this function:</p> <pre><code>function __2($string, $textdomain, $locale){ global $l10n; if(isset($l10n[$textdomain])) $backup = $l10n[$textdomain]; load_textdomain($textdomain, get_template_directory() . '/languages/'. $locale . '.mo'); $translation = __($string,$textdomain); if(isset($bkup)) $l10n[$textdomain] = $backup; return $translation; } </code></pre> <p>Now, as per this famous article, I really shouldn't have coded that function :</p> <p><a href="http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/" rel="nofollow noreferrer">http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/</a></p> <p>...But it simply works. So my question is: is it really ALWAYS wrong to pass variabled to l10n functions? An eventually why? And why shouldn't I use my function if it just works?</p>
[ { "answer_id": 274992, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>No it does not work, people that will need to translate the string will not be able to use the automated ...
2017/07/28
[ "https://wordpress.stackexchange.com/questions/274986", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10381/" ]
I needed to translate strings on another language than the current $locale, so I need to change the locale and restore it later, and I really couldn't repeat all the code for the 30++ strings I had to translate. So I ended up with this function: ``` function __2($string, $textdomain, $locale){ global $l10n; if(isset($l10n[$textdomain])) $backup = $l10n[$textdomain]; load_textdomain($textdomain, get_template_directory() . '/languages/'. $locale . '.mo'); $translation = __($string,$textdomain); if(isset($bkup)) $l10n[$textdomain] = $backup; return $translation; } ``` Now, as per this famous article, I really shouldn't have coded that function : <http://ottopress.com/2012/internationalization-youre-probably-doing-it-wrong/> ...But it simply works. So my question is: is it really ALWAYS wrong to pass variabled to l10n functions? An eventually why? And why shouldn't I use my function if it just works?
The answer is: sometimes. As long as you know what you are doing, there are no problems in terms of bugs. There can be situations where this is possible and safe, and other where it can be necessary or extremely useful. To complete and share the code above, I add the following: ``` function _e2($string, $textdomain, $locale){ echo __2($string, $textdomain, $locale); } // example _e2('hello','stratboy','it_IT'); ``` **UPDATE:** Some bonus code can be found here: [How to get a traslated string from a language other than the current one?](https://wordpress.stackexchange.com/questions/231685/how-to-get-a-traslated-string-from-a-language-other-than-the-current-one/274985#274985)
274,997
<p>I am using Woocommerce plugin for my custom product .and I am stuck with a situation .</p> <p>Does Woo commerce provide any hook or filter when refund is done through admin panel and refund will be manually.<a href="https://i.stack.imgur.com/z8mcA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/z8mcA.png" alt="For More details please see attached image "></a> </p>
[ { "answer_id": 296779, "author": "Tech Dog", "author_id": 138476, "author_profile": "https://wordpress.stackexchange.com/users/138476", "pm_score": 4, "selected": false, "text": "<p>Although this answer is little late but anyone else may get benefit from it. The <code>woocommerce_order_...
2017/07/28
[ "https://wordpress.stackexchange.com/questions/274997", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/98958/" ]
I am using Woocommerce plugin for my custom product .and I am stuck with a situation . Does Woo commerce provide any hook or filter when refund is done through admin panel and refund will be manually.[![For More details please see attached image ](https://i.stack.imgur.com/z8mcA.png)](https://i.stack.imgur.com/z8mcA.png)
Although this answer is little late but anyone else may get benefit from it. The `woocommerce_order_refunded` hook is called when an order is refunded. Use the following example: ``` // add the action add_action( 'woocommerce_order_refunded', 'action_woocommerce_order_refunded', 10, 2 ); // Do the magic function action_woocommerce_order_refunded( $order_id, $refund_id ) { // Your code here } ```
275,010
<ol> <li>On navigation, can a parent-grandchild menu appear? That is, are we able to pick and choose which categories we would like to suppress?</li> </ol> <p>Example: if taxonomy shows: Food>Fruit>Citrus>Oranges>Types of oranges Can we design the navigation to show: Fruit>Oranges>Types of oranges</p> <ol start="2"> <li><p>How many subcategories are possible?</p></li> <li><p>On navigation, can we rename categories on the front-end but keep a different taxonomy on the back end?</p></li> </ol> <p>Example: if taxonomy is: Food>Fruit>Citrus>Oranges>Types of oranges Can we actually have the users see these words instead (but they should experience navigation per the taxonomy?) Yummy things>Fruitilicious>Citrus</p>
[ { "answer_id": 296779, "author": "Tech Dog", "author_id": 138476, "author_profile": "https://wordpress.stackexchange.com/users/138476", "pm_score": 4, "selected": false, "text": "<p>Although this answer is little late but anyone else may get benefit from it. The <code>woocommerce_order_...
2017/07/28
[ "https://wordpress.stackexchange.com/questions/275010", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124756/" ]
1. On navigation, can a parent-grandchild menu appear? That is, are we able to pick and choose which categories we would like to suppress? Example: if taxonomy shows: Food>Fruit>Citrus>Oranges>Types of oranges Can we design the navigation to show: Fruit>Oranges>Types of oranges 2. How many subcategories are possible? 3. On navigation, can we rename categories on the front-end but keep a different taxonomy on the back end? Example: if taxonomy is: Food>Fruit>Citrus>Oranges>Types of oranges Can we actually have the users see these words instead (but they should experience navigation per the taxonomy?) Yummy things>Fruitilicious>Citrus
Although this answer is little late but anyone else may get benefit from it. The `woocommerce_order_refunded` hook is called when an order is refunded. Use the following example: ``` // add the action add_action( 'woocommerce_order_refunded', 'action_woocommerce_order_refunded', 10, 2 ); // Do the magic function action_woocommerce_order_refunded( $order_id, $refund_id ) { // Your code here } ```
275,018
<p>In my situation, style.css file has just package information and a comment as: All css files are placed in /css/ folder.</p> <p>In the css folder, I see a bunch of different styles and I don't exactly know which one controls what! </p> <p>Any suggestions on overriding the CSS rules from a child theme? </p>
[ { "answer_id": 296779, "author": "Tech Dog", "author_id": 138476, "author_profile": "https://wordpress.stackexchange.com/users/138476", "pm_score": 4, "selected": false, "text": "<p>Although this answer is little late but anyone else may get benefit from it. The <code>woocommerce_order_...
2017/07/28
[ "https://wordpress.stackexchange.com/questions/275018", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124648/" ]
In my situation, style.css file has just package information and a comment as: All css files are placed in /css/ folder. In the css folder, I see a bunch of different styles and I don't exactly know which one controls what! Any suggestions on overriding the CSS rules from a child theme?
Although this answer is little late but anyone else may get benefit from it. The `woocommerce_order_refunded` hook is called when an order is refunded. Use the following example: ``` // add the action add_action( 'woocommerce_order_refunded', 'action_woocommerce_order_refunded', 10, 2 ); // Do the magic function action_woocommerce_order_refunded( $order_id, $refund_id ) { // Your code here } ```
275,023
<p>I have made a plugin that uses a CPT and a few metadatas. The plugin comes in two versions A and B.</p> <p>Version A has one post meta less then version B called 'score'. When users update the plugin from A to B I need the score meta to be created for all custom posts for version B to work properly.</p> <p>This is the insert query I have used:</p> <pre><code>global $wpdb; $wpdb-&gt;query( " INSERT INTO $wpdb-&gt;postmeta (post_id,meta_key,meta_value) SELECT p.ID, 'score' AS meta_key, 0 AS meta_value FROM $wpdb-&gt;posts AS p WHERE p.post_type = 'my_cpt' " ); </code></pre> <p>This query works to add the new metadata but will create duplicates if runned multiple times. What should I do to make the query add the metadata only if it does not exist already?</p> <p>Thanks for any possible solution.</p>
[ { "answer_id": 275025, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 0, "selected": false, "text": "<p>You only want to <code>INSERT</code> for posts, that do not have this postmeta yet. So you need to change your...
2017/07/28
[ "https://wordpress.stackexchange.com/questions/275023", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124757/" ]
I have made a plugin that uses a CPT and a few metadatas. The plugin comes in two versions A and B. Version A has one post meta less then version B called 'score'. When users update the plugin from A to B I need the score meta to be created for all custom posts for version B to work properly. This is the insert query I have used: ``` global $wpdb; $wpdb->query( " INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) SELECT p.ID, 'score' AS meta_key, 0 AS meta_value FROM $wpdb->posts AS p WHERE p.post_type = 'my_cpt' " ); ``` This query works to add the new metadata but will create duplicates if runned multiple times. What should I do to make the query add the metadata only if it does not exist already? Thanks for any possible solution.
To anyone interested this is the query that worked for me: ``` INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) SELECT p.ID, 'score' AS meta_key, 0 AS meta_value FROM $wpdb->posts AS p WHERE p.post_type = 'my_cpt' AND p.ID NOT IN ( SELECT p2.ID FROM $wpdb->posts AS p2 INNER JOIN $wpdb->postmeta AS pm ON pm.post_id = p2.ID WHERE pm.meta_key = 'score' ) ``` But after reading [this article](https://www.percona.com/blog/2010/10/25/mysql-limitations-part-3-subqueries/) I preferred to split the query in two for better performance: ``` global $wpdb; //Get all posts which already have the metadata $not_in = $wpdb->get_results( " SELECT p.ID FROM $wpdb->posts AS p INNER JOIN $wpdb->postmeta AS pm ON pm.post_id = p.ID WHERE pm.meta_key = 'score' AND p.post_type = 'my-cpt' AND p.post_status NOT IN ('draft,auto-draft')", ARRAY_A ); //Make results into string $not_in = ! empty($not_in) ? implode( ',', array_column( $not_in, 'ID' ) ) : ''; //Insert new metadata $wpdb->query( " INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) SELECT p.ID, 'score' AS meta_key, 0 AS meta_value FROM $wpdb->posts AS p WHERE p.post_type = 'my-cpt' AND p.ID NOT IN ( $not_in ) " ); ```
275,030
<p>My theme has a top menu bar with accessibility shortcuts (jump to content, high contrast mode, etc). I need to include a link to an informational page describing the accessibility features available to visitors.</p> <p>This is a project for an University multisite network, with a lot of hosted sites, so I need a solution that doesn't require manually creating the page on each site. I also want to be able to easily update this content on future versions of the theme (i.e., inserting the content in the database of several sites may not be a good idea).</p> <p>I'm considering linking to the site's home page with some URL parameter, e.g. site1.example.com/?info=accessibility and addressing the content in the index.php, but that doesn't look too elegant. </p> <p>Any advice on a cleaner way to implement this?</p> <p>Thanks in advance!</p>
[ { "answer_id": 275044, "author": "Dub Scrib", "author_id": 75797, "author_profile": "https://wordpress.stackexchange.com/users/75797", "pm_score": 0, "selected": false, "text": "<p>If a plugin would work - see the WP Accessibility plugin. In Settings, 'Add Skiplinks' section, there's an ...
2017/07/28
[ "https://wordpress.stackexchange.com/questions/275030", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/68849/" ]
My theme has a top menu bar with accessibility shortcuts (jump to content, high contrast mode, etc). I need to include a link to an informational page describing the accessibility features available to visitors. This is a project for an University multisite network, with a lot of hosted sites, so I need a solution that doesn't require manually creating the page on each site. I also want to be able to easily update this content on future versions of the theme (i.e., inserting the content in the database of several sites may not be a good idea). I'm considering linking to the site's home page with some URL parameter, e.g. site1.example.com/?info=accessibility and addressing the content in the index.php, but that doesn't look too elegant. Any advice on a cleaner way to implement this? Thanks in advance!
I am assuming the following setup from reading your question: site.network.com site-2.network.com site-3.network.com where the main site exists on network.com (i.e. blog id `1`). All sites (or at least all subdomain sites) share the same theme. You need to be able to create a single content page and have that content available on all sites, i.e. \*.network.com/some-page/ --- The below covers using a page on the main site (id 1) as the content source (allowing you to update/edit that content via the editor), and a template file for a matching page title. You could include static content the same way. (see *Notes on Step 1* at the end). --- Step 1 ------ You can add a page template to the theme for a specific page, say, named *Accessibility* by duplicating the *page.php* and renaming it *page-accessibility.php* Step 2 ------ In *page-accessibility.php*, we will remove the normal loop, and replace it with some code to get a different page's content: the *Accessibility* page from the main site; using `switch_to_blog()`. If the main site id is `1`, the template page *page-accessibility.php* might look something like this: ``` get_header(); switch_to_blog(1); $post = get_page_by_title( 'Accessibility' ); if ($post) { $content = do_shortcode( html_entity_decode( $post->post_content ) ); } restore_current_blog(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php echo $content; ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); get_footer(); ``` Step 3 ------- Create an empty page named *Accessibility* for all sites. Rather than run something that would use `switch_to_blog()` to create a page for each one, we could instead check for the existence of the page on `init` of the site, and only create it if it doesn't exist. *functions.php of theme* ``` add_action( 'init', 'set_default_page' ); function set_default_page() { check_exists_create_page( 'Accessibility' ); //again, checking by title } function check_exists_create_page( $title ) { if ( get_page_by_title( $title ) == NULL ) { $args = array( 'post_title' => $title, 'post_content' => '', 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'page' ); wp_insert_post( $args ); } } ``` --- Notes on Step 1 --------------- You could also use this [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) to include static content. Remove the normal loop, and add your content directly or include another php file, etc. Then skip to Step 3 and create a page with a name that matches the *page-{your-page-name}.php* pattern for each site. Notes on Step 2 --------------- If you are wanting to use a site other than id`1`, you can always retrieve the id of the site you wish to use via [`get_current_blog_id()`](https://codex.wordpress.org/Function_Reference/get_current_blog_id) [`get_page_by_title()`](https://codex.wordpress.org/Function_Reference/get_page_by_title) uses title **not** slug. To get a page titled *My New Page*: `get_page_by_title( 'My New Page' )` Here I am just linking more info on [`do_shortcode()`](https://developer.wordpress.org/reference/functions/do_shortcode/) and [`html_entity_decode()`](http://php.net/manual/en/function.html-entity-decode.php). And for [`switch_to_blog()`](https://codex.wordpress.org/Function_Reference/switch_to_blog) and [`restore_current_blog()`](https://codex.wordpress.org/Function_Reference/restore_current_blog). Notes on Step 3 --------------- There may be a better hook than `init`. You could also add a conditional check if you wish to exclude some sites from this page check/creation. See my [answer on a different question](https://wordpress.stackexchange.com/a/275057/118366) if you need that. Be aware during testing that a page in Trash still exists.
275,038
<p>After migrating subdomain to new domain, not sure if the subdomain got left over in any of the settings.</p> <p>Where in PHPmyAdmin / SQL database should I find those subdomain urls and update them to the new one?</p> <p>(not even sure if my question makes sense).</p> <p>Any help will appreciated</p>
[ { "answer_id": 275044, "author": "Dub Scrib", "author_id": 75797, "author_profile": "https://wordpress.stackexchange.com/users/75797", "pm_score": 0, "selected": false, "text": "<p>If a plugin would work - see the WP Accessibility plugin. In Settings, 'Add Skiplinks' section, there's an ...
2017/07/28
[ "https://wordpress.stackexchange.com/questions/275038", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124762/" ]
After migrating subdomain to new domain, not sure if the subdomain got left over in any of the settings. Where in PHPmyAdmin / SQL database should I find those subdomain urls and update them to the new one? (not even sure if my question makes sense). Any help will appreciated
I am assuming the following setup from reading your question: site.network.com site-2.network.com site-3.network.com where the main site exists on network.com (i.e. blog id `1`). All sites (or at least all subdomain sites) share the same theme. You need to be able to create a single content page and have that content available on all sites, i.e. \*.network.com/some-page/ --- The below covers using a page on the main site (id 1) as the content source (allowing you to update/edit that content via the editor), and a template file for a matching page title. You could include static content the same way. (see *Notes on Step 1* at the end). --- Step 1 ------ You can add a page template to the theme for a specific page, say, named *Accessibility* by duplicating the *page.php* and renaming it *page-accessibility.php* Step 2 ------ In *page-accessibility.php*, we will remove the normal loop, and replace it with some code to get a different page's content: the *Accessibility* page from the main site; using `switch_to_blog()`. If the main site id is `1`, the template page *page-accessibility.php* might look something like this: ``` get_header(); switch_to_blog(1); $post = get_page_by_title( 'Accessibility' ); if ($post) { $content = do_shortcode( html_entity_decode( $post->post_content ) ); } restore_current_blog(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php echo $content; ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); get_footer(); ``` Step 3 ------- Create an empty page named *Accessibility* for all sites. Rather than run something that would use `switch_to_blog()` to create a page for each one, we could instead check for the existence of the page on `init` of the site, and only create it if it doesn't exist. *functions.php of theme* ``` add_action( 'init', 'set_default_page' ); function set_default_page() { check_exists_create_page( 'Accessibility' ); //again, checking by title } function check_exists_create_page( $title ) { if ( get_page_by_title( $title ) == NULL ) { $args = array( 'post_title' => $title, 'post_content' => '', 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'page' ); wp_insert_post( $args ); } } ``` --- Notes on Step 1 --------------- You could also use this [template hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) to include static content. Remove the normal loop, and add your content directly or include another php file, etc. Then skip to Step 3 and create a page with a name that matches the *page-{your-page-name}.php* pattern for each site. Notes on Step 2 --------------- If you are wanting to use a site other than id`1`, you can always retrieve the id of the site you wish to use via [`get_current_blog_id()`](https://codex.wordpress.org/Function_Reference/get_current_blog_id) [`get_page_by_title()`](https://codex.wordpress.org/Function_Reference/get_page_by_title) uses title **not** slug. To get a page titled *My New Page*: `get_page_by_title( 'My New Page' )` Here I am just linking more info on [`do_shortcode()`](https://developer.wordpress.org/reference/functions/do_shortcode/) and [`html_entity_decode()`](http://php.net/manual/en/function.html-entity-decode.php). And for [`switch_to_blog()`](https://codex.wordpress.org/Function_Reference/switch_to_blog) and [`restore_current_blog()`](https://codex.wordpress.org/Function_Reference/restore_current_blog). Notes on Step 3 --------------- There may be a better hook than `init`. You could also add a conditional check if you wish to exclude some sites from this page check/creation. See my [answer on a different question](https://wordpress.stackexchange.com/a/275057/118366) if you need that. Be aware during testing that a page in Trash still exists.
275,112
<pre><code>&lt;button name="button" style="margin: 20px 0 0 796px;padding: 3px 25px; background-color: red;color: white;font-weight: bold;" value="OK" type="button" &gt;HAVE A QUESTIONS&lt;/button&gt; </code></pre> <p>i make a button in my custom template page(header.php) but its display also my home page but i want to display only my custom template page.......how do i hide this button in my home page(front page)</p>
[ { "answer_id": 275116, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 1, "selected": false, "text": "<p>It's as simple as doing a conditional and check if you are on home.</p>\n\n<p>What you are looking for is <...
2017/07/29
[ "https://wordpress.stackexchange.com/questions/275112", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124815/" ]
``` <button name="button" style="margin: 20px 0 0 796px;padding: 3px 25px; background-color: red;color: white;font-weight: bold;" value="OK" type="button" >HAVE A QUESTIONS</button> ``` i make a button in my custom template page(header.php) but its display also my home page but i want to display only my custom template page.......how do i hide this button in my home page(front page)
It's as simple as doing a conditional and check if you are on home. What you are looking for is `is_page_template( );`. Wrap your button inside it as follows: ``` <?php if( is_page_template( 'your-template-slug.php' ) ){ ?> <button name="button" style=" ... " value="OK" type="button">HAVE A QUESTIONS</button> <?php } ?> ```
275,120
<p>I am trying to learn meta's in Wordpress by taking an example of the already existing meta →</p> <pre><code>function cpmb_display_meta_box( $post ) { // Define the nonce for security purposes wp_nonce_field( plugin_basename( __FILE__ ), 'cpmb-nonce-field' ); // Start the HTML string so that all other strings can be concatenated $html = ''; // If the current post has an invalid file type associated with it, // then display an error message. if ( 'invalid-file-type' == get_post_meta( $post-&gt;ID, 'mp3', true ) ) { $html .= '&lt;div id="invalid-file-type" class="error"&gt;'; $html .= '&lt;p&gt;You are trying to upload a file other than an MP3.&lt;/p&gt;'; $html .= '&lt;/div&gt;'; } // Display the 'Title of MP3' label and its text input element $html .= '&lt;label id="mp3-title" for="mp3-title"&gt;'; $html .= 'Title Of MP3'; $html .= '&lt;/label&gt;'; $html .= '&lt;input type="text" id="mp3-title" name="mp3-title" value="' . get_post_meta( $post-&gt;ID, 'mp3-title', true ) . '" placeholder="Your Song By Elton John" /&gt;'; // Display the 'MP3 File' label and its file input element $html .= '&lt;label id="mp3-file" for="mp3-file"&gt;'; $html .= 'MP3 File'; $html .= '&lt;/label&gt;'; $html .= '&lt;input type="file" id="mp3-file" name="mp3-file" value="" /&gt;'; echo $html; } </code></pre> <p>The above function is the function to render the markup in the backend?</p> <p>My question is related to this line →</p> <pre><code>if ( 'invalid-file-type' == get_post_meta( $post-&gt;ID, 'mp3', true ) ) { </code></pre> <p>It looks like to be validating whether the file is mp3 or not?</p> <p><strong>The Main Question →</strong> what if we want to validate whether this is Video file? Video files can be of multiple types and can come from many sources such Vimeo, Youtube, facebook etc.</p> <p>Additionally,</p> <p>I request the reader of this post to guide me to some specific meta where oembed has been used successfully.</p>
[ { "answer_id": 275122, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>The above function is the function to render the markup in the backend?</p>\n</blockquo...
2017/07/29
[ "https://wordpress.stackexchange.com/questions/275120", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
I am trying to learn meta's in Wordpress by taking an example of the already existing meta → ``` function cpmb_display_meta_box( $post ) { // Define the nonce for security purposes wp_nonce_field( plugin_basename( __FILE__ ), 'cpmb-nonce-field' ); // Start the HTML string so that all other strings can be concatenated $html = ''; // If the current post has an invalid file type associated with it, // then display an error message. if ( 'invalid-file-type' == get_post_meta( $post->ID, 'mp3', true ) ) { $html .= '<div id="invalid-file-type" class="error">'; $html .= '<p>You are trying to upload a file other than an MP3.</p>'; $html .= '</div>'; } // Display the 'Title of MP3' label and its text input element $html .= '<label id="mp3-title" for="mp3-title">'; $html .= 'Title Of MP3'; $html .= '</label>'; $html .= '<input type="text" id="mp3-title" name="mp3-title" value="' . get_post_meta( $post->ID, 'mp3-title', true ) . '" placeholder="Your Song By Elton John" />'; // Display the 'MP3 File' label and its file input element $html .= '<label id="mp3-file" for="mp3-file">'; $html .= 'MP3 File'; $html .= '</label>'; $html .= '<input type="file" id="mp3-file" name="mp3-file" value="" />'; echo $html; } ``` The above function is the function to render the markup in the backend? My question is related to this line → ``` if ( 'invalid-file-type' == get_post_meta( $post->ID, 'mp3', true ) ) { ``` It looks like to be validating whether the file is mp3 or not? **The Main Question →** what if we want to validate whether this is Video file? Video files can be of multiple types and can come from many sources such Vimeo, Youtube, facebook etc. Additionally, I request the reader of this post to guide me to some specific meta where oembed has been used successfully.
Post's metadata can not and should not be used for validation. They can be easily manipulated. Post metadata simply stores *"editable"* strings or arrays, nothing more than that. The code you have copied is trying to fetch a metadata and check if its value is `mp3`. You can change a value of `exe` to `mp3`, and it will assume that the file is mp3. So, security issue here. To validate a file truly, you have to pass the files path or URL to a real validator. For example, WordPress offers this function to validate an image: ``` file_is_valid_image( $path ); ``` Which returns true is the file in the pass is a real image. There are function to retrieve the file's *real* extension (since it can easily be manipulated, change .exe to .jpg), which you can find them by a simple search.
275,128
<p>I make a site of poetry. I would like to be able to display my text line by line (max 5) while it puts everything continuously.</p> <blockquote> <p>Search result:<br> Line 1<br> Line 2<br> Line 3<br> Line 4<br> Line 5</p> </blockquote> <p>On my excerpt I get this:<br> Line 1 Line 2 Line 3 Line 4 Line 5</p> <p>Can you give me a track to follow?</p> <p>Sorry, i'm french and my english is helped by google translate ;)</p> <p>EDIT</p> <p>Poetry original :<br></p> <blockquote> <p>Jour et nuit<br> Du Nord au Sud<br> D’Est en Ouest<br> En France, en Europe<br> Inlassablement,<br> Ils transportent des marchandises.<br> <br></p> </blockquote> <p>Excerpt :<br></p> <blockquote> <p>Jour et nuit Du Nord au Sud D’Est en Ouest En France, en Europe Inlassablement, Ils transportent des marchandises. <br> <br></p> </blockquote> <p>I would like :<br></p> <blockquote> <p>Jour et nuit<br> Du Nord au Sud<br> D’Est en Ouest<br> En France, en Europe<br> Inlassablement, [...]</p> </blockquote>
[ { "answer_id": 275147, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>An alternative way to look at the issue is that the excerpt is right and the way your post is being displ...
2017/07/29
[ "https://wordpress.stackexchange.com/questions/275128", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124824/" ]
I make a site of poetry. I would like to be able to display my text line by line (max 5) while it puts everything continuously. > > Search result: > Line 1 > Line 2 > Line 3 > Line 4 > Line 5 > > > On my excerpt I get this: Line 1 Line 2 Line 3 Line 4 Line 5 Can you give me a track to follow? Sorry, i'm french and my english is helped by google translate ;) EDIT Poetry original : > > Jour et nuit > Du Nord au Sud > D’Est en Ouest > En France, en > Europe > Inlassablement, > Ils transportent des marchandises. > > > > > > Excerpt : > > Jour et nuit Du Nord au Sud D’Est en Ouest En France, en Europe > Inlassablement, Ils transportent des marchandises. > > > > > I would like : > > Jour et nuit > Du Nord au Sud > D’Est en Ouest > En France, en > Europe > Inlassablement, [...] > > >
If you type your poets like this in the editor and separate them by new lines: > > This is a phrase > > > This is another phrase > > > Then you can divide them by new line, and then return them to the front-end. You can do this by using the `get_the_excerpt` filter. This goes in your theme's `functions.php` file: ``` apply_filters( 'get_the_excerpt', 'divide_by_newline' ); function divide_by_newline() { // Get the content of the poet $content = get_the_content(); // Let's trim the excerpt by default value of 55 words $content = wp_trim_words( $content , 55, '...' ); // Check if it's empty if( $content ) { // Divide the poets by new line $content_array = explode( "\n", $content ); // Store 5 of them into a string foreach( $content_array as $key=>$phrase ) { if( $key < 6 ) { $excerpt .= '<span class="poet-excerpt">'.$phrase.'</span>'; } } } else { $excerpt = ''; } // Return the data return $excerpt; } ``` Now, your excerpt's structure will be like this: ``` <span class="poet-excerpt">This is a phrase</span> <span class="poet-excerpt">This is another phrase</span> ``` We're not done yet. You have to change the default view of your spans. By default, a span is an inline element, it means they will not make a new line. By using this piece of CSS, we make them behave like blocks: ``` .poet-excerpt{ display:block; } ``` You can easily add this by heading to `Appearance > Customizer > Custom CSS` without modifying your `style.css`. But I have to mention, this works well only if you have a poet. This does not work for other excerpts. All done. Code is also poetry!
275,152
<p>I have a shordcode for Contact Form 7 form. I want use Advanced Custom Fields for ID value. How Can I do that?</p> <p>the ACF with ID value:</p> <pre><code>the_field('form'); </code></pre> <p>shordcode:</p> <pre><code>&lt;?php echo do_shortcode( '[contact-form-7 id="29"]' ); ?&gt; </code></pre> <p>Any solution? :)</p>
[ { "answer_id": 275155, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 3, "selected": true, "text": "<p>Simple as this:</p>\n\n<pre><code>&lt;?php echo do_shortcode( '[contact-form-7 id=\"'.get_field('form').'\"]...
2017/07/29
[ "https://wordpress.stackexchange.com/questions/275152", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116847/" ]
I have a shordcode for Contact Form 7 form. I want use Advanced Custom Fields for ID value. How Can I do that? the ACF with ID value: ``` the_field('form'); ``` shordcode: ``` <?php echo do_shortcode( '[contact-form-7 id="29"]' ); ?> ``` Any solution? :)
Simple as this: ``` <?php echo do_shortcode( '[contact-form-7 id="'.get_field('form').'"]' ); ?> ``` You have to notice, you should use `get_field()` to return the value. `the_field()` will echo it.
275,205
<p>I'm new to developing with WordPress. I read <a href="https://tommcfarlin.com/sending-data-post/" rel="nofollow noreferrer">here</a> that a good way to process data posted from forms is to insert an action on the init function like so:</p> <pre><code>add_action( 'init', 'contact_form_send_email' ); </code></pre> <p>My function seems to be processing the data correctly, but I can't figure out how to make a variable available within the same template that has the form.</p> <p>What is the way to do this? I've heard that setting global variables is not a good way to go.</p>
[ { "answer_id": 275224, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": true, "text": "<p>The difference between <code>add_action()</code> and <code>add_filter()</code> is semantic not technical, except...
2017/07/30
[ "https://wordpress.stackexchange.com/questions/275205", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/122408/" ]
I'm new to developing with WordPress. I read [here](https://tommcfarlin.com/sending-data-post/) that a good way to process data posted from forms is to insert an action on the init function like so: ``` add_action( 'init', 'contact_form_send_email' ); ``` My function seems to be processing the data correctly, but I can't figure out how to make a variable available within the same template that has the form. What is the way to do this? I've heard that setting global variables is not a good way to go.
The difference between `add_action()` and `add_filter()` is semantic not technical, except that a filter expects a returned value and an action does/will not. The question is whether `contact_form_send_email()` **needs** to be called-at /hooked-to `init`. If not, you can define your filter in the template with `apply_filters()`, and then hook to it to run your function and return a value to it. In *template page*: ``` $some_variable = 'some value'; $some_variable = apply_filters('my_filter_hook', $some_variable); ``` In *functions.php* ``` add_filter('my_filter_hook', 'contact_form_send_email', 10, 1 ); function contact_form_send_email( $some_variable ) { //do stuff $some_variable = 'some new value'; return $some_variable; } ``` --- To help determine where you need to hook, this [Actions Reference](https://codex.wordpress.org/Plugin_API/Action_Reference) can be useful. Scroll down and you will see some template specific hooks as well.
275,218
<p>i use wp-rest-api v2 plugin. Custom post types doesnt show taxonomy. somebody can tell me whats wrong?</p> <p>URL: /wp-json/wp/v2/galeri?_embed</p> <pre><code>{ "id": 275, "date": "2016-05-07T23:53:17", "date_gmt": "2016-05-07T20:53:17", "guid": { "rendered": "http:\/\/demo.markamiz.com\/?post_type=galeri&amp;#038;p=275" }, "modified": "2017-07-21T15:07:24", "modified_gmt": "2017-07-21T12:07:24", "slug": "samsung-galaxy-s7-edge", "status": "publish", "type": "galeri", "link": "http:\/\/www.teknoever.com\/galeri\/samsung-galaxy-s7-edge\/", "title": { "rendered": "Samsung Galaxy S7 Edge" }, "content": { "rendered": "&lt;p&gt;Toplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;1.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-276\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150604_samsung-galaxy-s7-1445005423.jpg\" alt=\"150604_samsung-galaxy-s7-1445005423\" width=\"580\" height=\"356\" \/&gt;&lt;br \/&gt;\n&lt;!--nextpage--&gt;&lt;br \/&gt;\nToplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;2.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-277\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150604_samsung-galaxy-s7-edge-concept-renders.jpg\" alt=\"150604_samsung-galaxy-s7-edge-concept-renders\" width=\"580\" height=\"386\" \/&gt;&lt;br \/&gt;\n&lt;!--nextpage--&gt;&lt;br \/&gt;\nToplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;3.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-278\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-1.jpg\" alt=\"150605_samsung-galaxy-s7-edge-concept-renders-1\" width=\"580\" height=\"386\" \/&gt;&lt;br \/&gt;\n&lt;!--nextpage--&gt;&lt;br \/&gt;\nToplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;4.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-279\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg\" alt=\"150605_samsung-galaxy-s7-edge-concept-renders-2\" width=\"580\" height=\"386\" \/&gt;&lt;br \/&gt;\n&lt;!--nextpage--&gt;&lt;br \/&gt;\nToplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;5.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-280\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-3-1445005456.jpg\" alt=\"150605_samsung-galaxy-s7-edge-concept-renders-3-1445005456\" width=\"580\" height=\"385\" \/&gt;&lt;br \/&gt;\n&lt;!--nextpage--&gt;&lt;br \/&gt;\nToplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;6.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-281\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150606_samsung-galaxy-s7-edge-concept-renders-4.jpg\" alt=\"150606_samsung-galaxy-s7-edge-concept-renders-4\" width=\"580\" height=\"386\" \/&gt;&lt;br \/&gt;\n&lt;!--nextpage--&gt;&lt;br \/&gt;\nToplam &lt;b&gt;7&lt;\/b&gt; sayfadan &lt;b&gt;7.&lt;\/b&gt; sayfadas\u0131n\u0131z.&lt;br \/&gt;\n&lt;img class=\"alignnone size-full wp-image-282\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150606_samsung-galaxy-s7-edge-concept-renders-5-1.jpg\" alt=\"150606_samsung-galaxy-s7-edge-concept-renders-5\" width=\"580\" height=\"386\" \/&gt;&lt;\/p&gt;\n", "protected": false }, "excerpt": { "rendered": "&lt;p&gt;Y\u0131l\u0131n en dikkat \u00e7ekici modellerinden bir tanesi olan Samsung Galaxy S7 edge, inceleme merkezimizin yeni konu\u011fu oluyor.&lt;br \/&gt;\nSamsung, ge\u00e7ti\u011fimiz y\u0131l sat\u0131\u015fa sundu\u011fu Galaxy S6 ve Galaxy S6 edge modelleriyle tasar\u0131m dilinde ciddi bir de\u011fi\u015fikli\u011fe gitmi\u015f, plastik tasar\u0131m\u0131 tarihin tozlu sayfalar\u0131nda b\u0131rakarak cam ve metal malzemelerle haz\u0131rlanan premium tasar\u0131mlar\u0131 bizlere sunmu\u015ftu. \u00d6zellikle S6 edge ve daha sonra sat\u0131\u015fa sunulan S6 edge+, y\u0131l\u0131n en \u015f\u0131k modelleri aras\u0131nda g\u00f6sterilmi\u015fti.&lt;\/p&gt;\n", "protected": false }, "author": 4, "featured_media": 7825, "menu_order": 0, "comment_status": "open", "ping_status": "open", "template": "", "meta": [], "acf": [], "_links": { "self": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/galeri\/275" }], "collection": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/galeri" }], "about": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/types\/galeri" }], "author": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users\/4" }], "replies": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/comments?post=275" }], "version-history": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/galeri\/275\/revisions" }], "wp:featuredmedia": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media\/7825" }], "wp:attachment": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media?parent=275" }], "curies": [{ "name": "wp", "href": "https:\/\/api.w.org\/{rel}", "templated": true }] }, "_embedded": { "author": [{ "id": 4, "name": "Erdin\u00e7", "url": "http:\/\/www.teknoever.com", "description": "Uzun y\u0131llar bir\u00e7ok blog ve haber portallar\u0131nda edit\u00f6r olarak \u00e7al\u0131\u015fmas\u0131n\u0131n yan\u0131nda, asp ve php yaz\u0131l\u0131mlar\u0131na olduk\u00e7a hakim ve bir\u00e7ok projede b\u00fcy\u00fck ba\u015far\u0131lara imza atm\u0131\u015ft\u0131r. Edit\u00f6rl\u00fck kariyerinde \u015fimdi Tekno Ever ile devam etmektedir.Referanslar i\u00e7in l\u00fctfen markamiz.com'u ziyaret ediniz.", "link": "http:\/\/www.teknoever.com\/yazar\/erdinc\/", "slug": "erdinc", "avatar_urls": { "24": "http:\/\/2.gravatar.com\/avatar\/b37cac9cdbbc2f7cdae3348e514a305b?s=24&amp;d=mm&amp;r=g", "48": "http:\/\/2.gravatar.com\/avatar\/b37cac9cdbbc2f7cdae3348e514a305b?s=48&amp;d=mm&amp;r=g", "96": "http:\/\/2.gravatar.com\/avatar\/b37cac9cdbbc2f7cdae3348e514a305b?s=96&amp;d=mm&amp;r=g" }, "acf": [], "_links": { "self": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users\/4" }], "collection": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users" }] } }], "wp:featuredmedia": [{ "id": 7825, "date": "2016-09-06T17:31:52", "slug": "150605_samsung-galaxy-s7-edge-concept-renders-2", "type": "attachment", "link": "http:\/\/www.teknoever.com\/galeri\/samsung-galaxy-s7-edge\/150605_samsung-galaxy-s7-edge-concept-renders-2\/", "title": { "rendered": "150605_samsung-galaxy-s7-edge-concept-renders-2" }, "author": 4, "acf": [], "caption": { "rendered": "" }, "alt_text": "", "media_type": "image", "mime_type": "image\/jpeg", "media_details": { "width": 580, "height": 386, "file": "2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg", "sizes": { "thumbnail": { "file": "150605_samsung-galaxy-s7-edge-concept-renders-2-150x150.jpg", "width": 150, "height": 150, "mime_type": "image\/jpeg", "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2-150x150.jpg" }, "medium": { "file": "150605_samsung-galaxy-s7-edge-concept-renders-2-300x200.jpg", "width": 300, "height": 200, "mime_type": "image\/jpeg", "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2-300x200.jpg" }, "full": { "file": "150605_samsung-galaxy-s7-edge-concept-renders-2.jpg", "width": 580, "height": 386, "mime_type": "image\/jpeg", "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg" } }, "image_meta": { "aperture": "0", "credit": "", "camera": "", "caption": "", "created_timestamp": "0", "copyright": "", "focal_length": "0", "iso": "0", "shutter_speed": "0", "title": "", "orientation": "0", "keywords": [] } }, "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg", "_links": { "self": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media\/7825" }], "collection": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media" }], "about": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/types\/attachment" }], "author": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users\/4" }], "replies": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/comments?post=7825" }] } }] } } </code></pre>
[ { "answer_id": 275224, "author": "hwl", "author_id": 118366, "author_profile": "https://wordpress.stackexchange.com/users/118366", "pm_score": 3, "selected": true, "text": "<p>The difference between <code>add_action()</code> and <code>add_filter()</code> is semantic not technical, except...
2017/07/30
[ "https://wordpress.stackexchange.com/questions/275218", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93283/" ]
i use wp-rest-api v2 plugin. Custom post types doesnt show taxonomy. somebody can tell me whats wrong? URL: /wp-json/wp/v2/galeri?\_embed ``` { "id": 275, "date": "2016-05-07T23:53:17", "date_gmt": "2016-05-07T20:53:17", "guid": { "rendered": "http:\/\/demo.markamiz.com\/?post_type=galeri&#038;p=275" }, "modified": "2017-07-21T15:07:24", "modified_gmt": "2017-07-21T12:07:24", "slug": "samsung-galaxy-s7-edge", "status": "publish", "type": "galeri", "link": "http:\/\/www.teknoever.com\/galeri\/samsung-galaxy-s7-edge\/", "title": { "rendered": "Samsung Galaxy S7 Edge" }, "content": { "rendered": "<p>Toplam <b>7<\/b> sayfadan <b>1.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-276\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150604_samsung-galaxy-s7-1445005423.jpg\" alt=\"150604_samsung-galaxy-s7-1445005423\" width=\"580\" height=\"356\" \/><br \/>\n<!--nextpage--><br \/>\nToplam <b>7<\/b> sayfadan <b>2.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-277\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150604_samsung-galaxy-s7-edge-concept-renders.jpg\" alt=\"150604_samsung-galaxy-s7-edge-concept-renders\" width=\"580\" height=\"386\" \/><br \/>\n<!--nextpage--><br \/>\nToplam <b>7<\/b> sayfadan <b>3.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-278\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-1.jpg\" alt=\"150605_samsung-galaxy-s7-edge-concept-renders-1\" width=\"580\" height=\"386\" \/><br \/>\n<!--nextpage--><br \/>\nToplam <b>7<\/b> sayfadan <b>4.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-279\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg\" alt=\"150605_samsung-galaxy-s7-edge-concept-renders-2\" width=\"580\" height=\"386\" \/><br \/>\n<!--nextpage--><br \/>\nToplam <b>7<\/b> sayfadan <b>5.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-280\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-3-1445005456.jpg\" alt=\"150605_samsung-galaxy-s7-edge-concept-renders-3-1445005456\" width=\"580\" height=\"385\" \/><br \/>\n<!--nextpage--><br \/>\nToplam <b>7<\/b> sayfadan <b>6.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-281\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150606_samsung-galaxy-s7-edge-concept-renders-4.jpg\" alt=\"150606_samsung-galaxy-s7-edge-concept-renders-4\" width=\"580\" height=\"386\" \/><br \/>\n<!--nextpage--><br \/>\nToplam <b>7<\/b> sayfadan <b>7.<\/b> sayfadas\u0131n\u0131z.<br \/>\n<img class=\"alignnone size-full wp-image-282\" src=\"http:\/\/demo.markamiz.com\/wp-content\/uploads\/2016\/05\/150606_samsung-galaxy-s7-edge-concept-renders-5-1.jpg\" alt=\"150606_samsung-galaxy-s7-edge-concept-renders-5\" width=\"580\" height=\"386\" \/><\/p>\n", "protected": false }, "excerpt": { "rendered": "<p>Y\u0131l\u0131n en dikkat \u00e7ekici modellerinden bir tanesi olan Samsung Galaxy S7 edge, inceleme merkezimizin yeni konu\u011fu oluyor.<br \/>\nSamsung, ge\u00e7ti\u011fimiz y\u0131l sat\u0131\u015fa sundu\u011fu Galaxy S6 ve Galaxy S6 edge modelleriyle tasar\u0131m dilinde ciddi bir de\u011fi\u015fikli\u011fe gitmi\u015f, plastik tasar\u0131m\u0131 tarihin tozlu sayfalar\u0131nda b\u0131rakarak cam ve metal malzemelerle haz\u0131rlanan premium tasar\u0131mlar\u0131 bizlere sunmu\u015ftu. \u00d6zellikle S6 edge ve daha sonra sat\u0131\u015fa sunulan S6 edge+, y\u0131l\u0131n en \u015f\u0131k modelleri aras\u0131nda g\u00f6sterilmi\u015fti.<\/p>\n", "protected": false }, "author": 4, "featured_media": 7825, "menu_order": 0, "comment_status": "open", "ping_status": "open", "template": "", "meta": [], "acf": [], "_links": { "self": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/galeri\/275" }], "collection": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/galeri" }], "about": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/types\/galeri" }], "author": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users\/4" }], "replies": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/comments?post=275" }], "version-history": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/galeri\/275\/revisions" }], "wp:featuredmedia": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media\/7825" }], "wp:attachment": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media?parent=275" }], "curies": [{ "name": "wp", "href": "https:\/\/api.w.org\/{rel}", "templated": true }] }, "_embedded": { "author": [{ "id": 4, "name": "Erdin\u00e7", "url": "http:\/\/www.teknoever.com", "description": "Uzun y\u0131llar bir\u00e7ok blog ve haber portallar\u0131nda edit\u00f6r olarak \u00e7al\u0131\u015fmas\u0131n\u0131n yan\u0131nda, asp ve php yaz\u0131l\u0131mlar\u0131na olduk\u00e7a hakim ve bir\u00e7ok projede b\u00fcy\u00fck ba\u015far\u0131lara imza atm\u0131\u015ft\u0131r. Edit\u00f6rl\u00fck kariyerinde \u015fimdi Tekno Ever ile devam etmektedir.Referanslar i\u00e7in l\u00fctfen markamiz.com'u ziyaret ediniz.", "link": "http:\/\/www.teknoever.com\/yazar\/erdinc\/", "slug": "erdinc", "avatar_urls": { "24": "http:\/\/2.gravatar.com\/avatar\/b37cac9cdbbc2f7cdae3348e514a305b?s=24&d=mm&r=g", "48": "http:\/\/2.gravatar.com\/avatar\/b37cac9cdbbc2f7cdae3348e514a305b?s=48&d=mm&r=g", "96": "http:\/\/2.gravatar.com\/avatar\/b37cac9cdbbc2f7cdae3348e514a305b?s=96&d=mm&r=g" }, "acf": [], "_links": { "self": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users\/4" }], "collection": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users" }] } }], "wp:featuredmedia": [{ "id": 7825, "date": "2016-09-06T17:31:52", "slug": "150605_samsung-galaxy-s7-edge-concept-renders-2", "type": "attachment", "link": "http:\/\/www.teknoever.com\/galeri\/samsung-galaxy-s7-edge\/150605_samsung-galaxy-s7-edge-concept-renders-2\/", "title": { "rendered": "150605_samsung-galaxy-s7-edge-concept-renders-2" }, "author": 4, "acf": [], "caption": { "rendered": "" }, "alt_text": "", "media_type": "image", "mime_type": "image\/jpeg", "media_details": { "width": 580, "height": 386, "file": "2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg", "sizes": { "thumbnail": { "file": "150605_samsung-galaxy-s7-edge-concept-renders-2-150x150.jpg", "width": 150, "height": 150, "mime_type": "image\/jpeg", "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2-150x150.jpg" }, "medium": { "file": "150605_samsung-galaxy-s7-edge-concept-renders-2-300x200.jpg", "width": 300, "height": 200, "mime_type": "image\/jpeg", "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2-300x200.jpg" }, "full": { "file": "150605_samsung-galaxy-s7-edge-concept-renders-2.jpg", "width": 580, "height": 386, "mime_type": "image\/jpeg", "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg" } }, "image_meta": { "aperture": "0", "credit": "", "camera": "", "caption": "", "created_timestamp": "0", "copyright": "", "focal_length": "0", "iso": "0", "shutter_speed": "0", "title": "", "orientation": "0", "keywords": [] } }, "source_url": "http:\/\/www.teknoever.com\/wp-content\/uploads\/2016\/05\/150605_samsung-galaxy-s7-edge-concept-renders-2.jpg", "_links": { "self": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media\/7825" }], "collection": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/media" }], "about": [{ "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/types\/attachment" }], "author": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/users\/4" }], "replies": [{ "embeddable": true, "href": "http:\/\/www.teknoever.com\/wp-json\/wp\/v2\/comments?post=7825" }] } }] } } ```
The difference between `add_action()` and `add_filter()` is semantic not technical, except that a filter expects a returned value and an action does/will not. The question is whether `contact_form_send_email()` **needs** to be called-at /hooked-to `init`. If not, you can define your filter in the template with `apply_filters()`, and then hook to it to run your function and return a value to it. In *template page*: ``` $some_variable = 'some value'; $some_variable = apply_filters('my_filter_hook', $some_variable); ``` In *functions.php* ``` add_filter('my_filter_hook', 'contact_form_send_email', 10, 1 ); function contact_form_send_email( $some_variable ) { //do stuff $some_variable = 'some new value'; return $some_variable; } ``` --- To help determine where you need to hook, this [Actions Reference](https://codex.wordpress.org/Plugin_API/Action_Reference) can be useful. Scroll down and you will see some template specific hooks as well.
275,263
<p>I'm making an ajax request from my primary domain to a subdomain. I've solved my cross origin issues so I'm not getting an error. The call is returning <code>data:0</code>. I've checked my response config and the ajax url is correct as well as "action". My <code>functions.php</code> looks like this:</p> <pre><code>add_action("wp_ajax_sendhire", "sendhire"); add_action("wp_ajax_nopriv_sendhire", "sendhire"); function sendhire() { $cars = array("Volvo", "BMW", "Toyota"); return json_encode($cars); die(); } </code></pre> <p>The data, obviously, is just for testing.</p>
[ { "answer_id": 275264, "author": "Johansson", "author_id": 94498, "author_profile": "https://wordpress.stackexchange.com/users/94498", "pm_score": 0, "selected": false, "text": "<p>If you want to use Admin-Ajax to output the content, you should use <code>echo</code> instead. There is not...
2017/07/31
[ "https://wordpress.stackexchange.com/questions/275263", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/8278/" ]
I'm making an ajax request from my primary domain to a subdomain. I've solved my cross origin issues so I'm not getting an error. The call is returning `data:0`. I've checked my response config and the ajax url is correct as well as "action". My `functions.php` looks like this: ``` add_action("wp_ajax_sendhire", "sendhire"); add_action("wp_ajax_nopriv_sendhire", "sendhire"); function sendhire() { $cars = array("Volvo", "BMW", "Toyota"); return json_encode($cars); die(); } ``` The data, obviously, is just for testing.
If you want to use Admin-Ajax to output the content, you should use `echo` instead. There is nothing to be viewed when you use `return`, so you'll get a `0`. This quotation from the codex explains further about the `0` response: > > If the Ajax request fails in `wp-admin/admin-ajax.php`, the response > will be -1 or 0, depending on the reason for the failure. > Additionally, if the request succeeds, but the Ajax action does not > match a WordPress hook defined with `add_action('wp_ajax_(action)', > ...)` or `add_action('wp_ajax_nopriv_(action)', ...)`, then > `admin-ajax.php` will respond 0. > > > Now, if you are going to output a JSON response, you should take a look into the REST API. Its default response type is JSON. To do so, register a path for the endpoint, and create a callback function: ``` add_action( 'rest_api_init', function () { register_rest_route( 'dcp3450', '/test_endpoint/', array( 'methods' => 'GET', 'callback' => 'sendhire' ) ); }); function sendhire() { $cars = array("Volvo", "BMW", "Toyota"); return $cars; } ``` Now by accessing `http://example.com/wp-json/dcp3450/test_endpoint/` you will get your JSON response, and you can get rid of this annoying 0 that is following humanity to its end.
275,301
<p>I followed the instructions given in this <a href="https://getflywheel.com/layout/how-to-create-custom-meta-boxes-with-cmb2/" rel="nofollow noreferrer">blog</a> to set the CMB2 plugin, but it is not working in my case.</p> <p>theme-meta-function.php →</p> <pre><code> &lt;?php /** * Include and set up custom metaboxes and fields. (Make sure you copy this file outside the CMB2 directory) * * Be sure to replace all instances of 'yourprefix_' with your project's prefix. * http://nacin.com/2010/05/11/in-wordpress-prefix-everything/ * * @category YourThemeOrPlugin * @package Demo_CMB2 * @license http://www.opensource.org/licenses/gpl-license.php GPL v2.0 (or later) * @link https://github.com/WebDevStudios/CMB2 */ /** * Get the bootstrap! If using the plugin from wordpress.org, REMOVE THIS! */ add_action( 'cmb2_admin_init', 'register_testimonial_metabox' ); /** * Hook in and add a testimonial metabox. Can only happen on the 'cmb2_admin_init' or 'cmb2_init' hook. */ function register_testimonial_metabox() { // Start with an underscore to hide fields from custom fields list $prefix = '_yourprefix_'; //note, you can use anything you'd like here /** * Start field groups here */ // This first field group tells WordPress where to put the fields. In the example below, it is set to show up only on Post_ID=10 $cmb_demo = new_cmb2_box( array( 'id' =&gt; $prefix . 'metabox', 'title' =&gt; __( 'Homepage Custom Fields', 'cmb2' ), 'object_types' =&gt; array( 'page', ), // Post type 'show_on' =&gt; array( 'id' =&gt; array( 10, ) ), // Specific post IDs to display this metabox ) ); $cmb_demo-&gt;add_field( array( 'name' =&gt; __( 'Testimonial Author', 'cmb2' ), 'desc' =&gt; __( 'Who is the testimonial from', 'cmb2' ), 'id' =&gt; $prefix . 'author', //Note, I renamed this to be more appropriate 'type' =&gt; 'textarea_small', ) ); $cmb_demo-&gt;add_field( array( 'name' =&gt; __( 'Testimonial', 'cmb2' ), 'desc' =&gt; __( 'add the testimonial here', 'cmb2' ), 'id' =&gt; $prefix . 'testimonial', //Note, I renamed this to be more appropriate 'type' =&gt; 'wysiwyg', 'options' =&gt; array( 'textarea_rows' =&gt; 5, ), ) ); $cmb_demo-&gt;add_field( array( 'name' =&gt; __( 'Author Image', 'cmb2' ), 'desc' =&gt; __( 'Upload an image or enter a URL.', 'cmb2' ), 'id' =&gt; $prefix . 'image', //Note, I renamed this to be more appropriate 'type' =&gt; 'file', ) ); } </code></pre> <p>then I have included like this in the functions.php →</p> <pre><code>require_once( dirname(__FILE__) . '/inc/lib/theme-meta-functions.php'); </code></pre> <p>But not a single meta is appearing the post → <a href="https://www.screencast.com/t/Bvihe62fZMV" rel="nofollow noreferrer">https://www.screencast.com/t/Bvihe62fZMV</a></p> <p>I forget to mention that the <strong>plugin is already installed</strong> in the <strong>Wordpress</strong>.</p>
[ { "answer_id": 275303, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 1, "selected": false, "text": "<p>Change <code>$prefix = '_yourprefix_';</code> to <code>$prefix = '_wp';</code></p>\n\n<p>or add the c...
2017/07/31
[ "https://wordpress.stackexchange.com/questions/275301", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/105791/" ]
I followed the instructions given in this [blog](https://getflywheel.com/layout/how-to-create-custom-meta-boxes-with-cmb2/) to set the CMB2 plugin, but it is not working in my case. theme-meta-function.php → ``` <?php /** * Include and set up custom metaboxes and fields. (Make sure you copy this file outside the CMB2 directory) * * Be sure to replace all instances of 'yourprefix_' with your project's prefix. * http://nacin.com/2010/05/11/in-wordpress-prefix-everything/ * * @category YourThemeOrPlugin * @package Demo_CMB2 * @license http://www.opensource.org/licenses/gpl-license.php GPL v2.0 (or later) * @link https://github.com/WebDevStudios/CMB2 */ /** * Get the bootstrap! If using the plugin from wordpress.org, REMOVE THIS! */ add_action( 'cmb2_admin_init', 'register_testimonial_metabox' ); /** * Hook in and add a testimonial metabox. Can only happen on the 'cmb2_admin_init' or 'cmb2_init' hook. */ function register_testimonial_metabox() { // Start with an underscore to hide fields from custom fields list $prefix = '_yourprefix_'; //note, you can use anything you'd like here /** * Start field groups here */ // This first field group tells WordPress where to put the fields. In the example below, it is set to show up only on Post_ID=10 $cmb_demo = new_cmb2_box( array( 'id' => $prefix . 'metabox', 'title' => __( 'Homepage Custom Fields', 'cmb2' ), 'object_types' => array( 'page', ), // Post type 'show_on' => array( 'id' => array( 10, ) ), // Specific post IDs to display this metabox ) ); $cmb_demo->add_field( array( 'name' => __( 'Testimonial Author', 'cmb2' ), 'desc' => __( 'Who is the testimonial from', 'cmb2' ), 'id' => $prefix . 'author', //Note, I renamed this to be more appropriate 'type' => 'textarea_small', ) ); $cmb_demo->add_field( array( 'name' => __( 'Testimonial', 'cmb2' ), 'desc' => __( 'add the testimonial here', 'cmb2' ), 'id' => $prefix . 'testimonial', //Note, I renamed this to be more appropriate 'type' => 'wysiwyg', 'options' => array( 'textarea_rows' => 5, ), ) ); $cmb_demo->add_field( array( 'name' => __( 'Author Image', 'cmb2' ), 'desc' => __( 'Upload an image or enter a URL.', 'cmb2' ), 'id' => $prefix . 'image', //Note, I renamed this to be more appropriate 'type' => 'file', ) ); } ``` then I have included like this in the functions.php → ``` require_once( dirname(__FILE__) . '/inc/lib/theme-meta-functions.php'); ``` But not a single meta is appearing the post → <https://www.screencast.com/t/Bvihe62fZMV> I forget to mention that the **plugin is already installed** in the **Wordpress**.
the solution → ``` 'object_types' => array( 'page', ), // Post type 'show_on' => array( 'id' => array( 10, ) ), // Specific post IDs to display this metabox ``` the above was the reason why it was not working on a post. I just added post and added it here → ``` 'object_types' => array( 'page', ), // Post type ``` and deleted this line → ``` 'show_on' => array( 'id' => array( 10, ) ), // Specific post ``` It all started to work, and there was no issue in the plugin or any piece of code.
275,305
<p>For some of my larger WordPress sites, I would like to avoid having to copy all the media files from the live site to the development site, but instead point the development site to use the media files from the live site.</p> <p>On Drupal there is a great module for this called Stage File Proxy: <a href="https://www.drupal.org/project/stage_file_proxy" rel="nofollow noreferrer">https://www.drupal.org/project/stage_file_proxy</a></p> <p>How can I do it with Wordpress?</p>
[ { "answer_id": 275303, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 1, "selected": false, "text": "<p>Change <code>$prefix = '_yourprefix_';</code> to <code>$prefix = '_wp';</code></p>\n\n<p>or add the c...
2017/07/31
[ "https://wordpress.stackexchange.com/questions/275305", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/85504/" ]
For some of my larger WordPress sites, I would like to avoid having to copy all the media files from the live site to the development site, but instead point the development site to use the media files from the live site. On Drupal there is a great module for this called Stage File Proxy: <https://www.drupal.org/project/stage_file_proxy> How can I do it with Wordpress?
the solution → ``` 'object_types' => array( 'page', ), // Post type 'show_on' => array( 'id' => array( 10, ) ), // Specific post IDs to display this metabox ``` the above was the reason why it was not working on a post. I just added post and added it here → ``` 'object_types' => array( 'page', ), // Post type ``` and deleted this line → ``` 'show_on' => array( 'id' => array( 10, ) ), // Specific post ``` It all started to work, and there was no issue in the plugin or any piece of code.
275,310
<p>i tried to create a simple function to receive a email when a specify user is logged, i tried with $current_user->ID and also with wp_get_current_user() but not working. This is my code:</p> <pre><code>function InvioMail() { global $current_user; $ID = $current_user-&gt;ID; $user = wp_get_current_user(); $name = $user-&gt;user_login; if ($name == 'piero') { $to = 'example@mail.com'; $subject = 'test su action hook wp_login'; $body = 'test su action hook pwp_login'; $headers = array('Content-Type: text/html; charset=UTF-8','From: My Site Name &lt;support@example.com'); wp_mail( $to, $subject, $body, $headers ); } } add_action( 'wp_login', 'InvioMail'); </code></pre> <p>Without if condition work property but when i try with IF nothing.</p> <p>Where I'm wrong?</p>
[ { "answer_id": 275315, "author": "Nuno Sarmento", "author_id": 75461, "author_profile": "https://wordpress.stackexchange.com/users/75461", "pm_score": 0, "selected": false, "text": "<p>Try the code below. </p>\n\n<pre><code>function InvioMail() {\n global $current_user;\n\n if ($curren...
2017/07/31
[ "https://wordpress.stackexchange.com/questions/275310", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124940/" ]
i tried to create a simple function to receive a email when a specify user is logged, i tried with $current\_user->ID and also with wp\_get\_current\_user() but not working. This is my code: ``` function InvioMail() { global $current_user; $ID = $current_user->ID; $user = wp_get_current_user(); $name = $user->user_login; if ($name == 'piero') { $to = 'example@mail.com'; $subject = 'test su action hook wp_login'; $body = 'test su action hook pwp_login'; $headers = array('Content-Type: text/html; charset=UTF-8','From: My Site Name <support@example.com'); wp_mail( $to, $subject, $body, $headers ); } } add_action( 'wp_login', 'InvioMail'); ``` Without if condition work property but when i try with IF nothing. Where I'm wrong?
This should work for you, make sure that the `user_login` or `user_id` matches to the string you're using in the condition. Try to do a `var_dump($user_login);` And about the function you're using, you don't need to grab the `global` or call `get_current_user();`, because the action you're calling already pass two parameters to your function, the first is a `string` with the `$user_login`, and the second is a `WP_User object` the current logged in user. To use it, just change your code to this: ``` function InvioMail($user_login, $user) { if ($user_login == 'piero') { $to = 'example@mail.com'; $subject = 'test su action hook wp_login'; $body = 'test su action hook pwp_login'; $headers = array('Content-Type: text/html; charset=UTF-8','From: My Site Name <support@example.com'); wp_mail( $to, $subject, $body, $headers ); } } add_action( 'wp_login', 'InvioMail', 10, 2); ``` To learn more about this hook, check the [Docs](https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login).
275,367
<p>I am trying to create a form for customers to fill out after they have purchased a subscription and/or when they return to the site and log in. My site has multiple subscription products and I need the form to be conditional based on which product they chose. To see whether they have an active subscription I am using this code:</p> <pre><code>$customer_orders = get_posts( array( 'numberposts' =&gt; -1, 'meta_key' =&gt; '_customer_user', 'meta_value' =&gt; get_current_user_id(), 'post_type' =&gt; 'shop_subscription', 'post_status' =&gt; array_keys( wc_get_order_statuses() ), ) ); </code></pre> <p>This only returns the subscription id and status. I need to know which product was purchased with the subscription. Any help is much appreciated. Thanks!</p>
[ { "answer_id": 313071, "author": "Aliiiiiiii", "author_id": 132815, "author_profile": "https://wordpress.stackexchange.com/users/132815", "pm_score": 2, "selected": false, "text": "<p>Using the Id of a subscription you can get the subscription object :</p>\n\n<pre><code>$subscription_obj...
2017/07/31
[ "https://wordpress.stackexchange.com/questions/275367", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124972/" ]
I am trying to create a form for customers to fill out after they have purchased a subscription and/or when they return to the site and log in. My site has multiple subscription products and I need the form to be conditional based on which product they chose. To see whether they have an active subscription I am using this code: ``` $customer_orders = get_posts( array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => get_current_user_id(), 'post_type' => 'shop_subscription', 'post_status' => array_keys( wc_get_order_statuses() ), ) ); ``` This only returns the subscription id and status. I need to know which product was purchased with the subscription. Any help is much appreciated. Thanks!
Using the Id of a subscription you can get the subscription object : ``` $subscription_obj = wcs_get_subscription($sub_id); ``` wcs\_get\_subscription is a wrapper for the wc\_get\_order() method Then get items of your subscription : ``` $items = $subscription_obj ->get_items(); ```
275,370
<p>I'm trying to develop a theme. but "Display Site Title and Tagline" checkbox not working nothing change when i check or uncheck the site tile and tagline still exist. also the color option not giving any effect? please help my code for the header text is:</p> <pre><code>&lt;header class="image-bg-fluid-height" id="startchange" style="background-image: url('&lt;?php echo( get_header_image() ); ?&gt;')" &gt; &lt;h1 class="h1-hdr"&gt;&lt;?php bloginfo('name');?&gt; &lt;/h1&gt; &lt;br/&gt; &lt;br/&gt; &lt;P id="header-pa"&gt;&lt;?php bloginfo('description');?&gt; &lt;/P&gt; &lt;a class="btn btn-primary btn-lg outline " role="button" href="#" id="btn-header"&gt;WATCH A VIDEO&lt;/a&gt; &lt;br/&gt; &lt;br/&gt; &lt;/header&gt; </code></pre>
[ { "answer_id": 281513, "author": "IBRAHIM EZZAT", "author_id": 120259, "author_profile": "https://wordpress.stackexchange.com/users/120259", "pm_score": 3, "selected": true, "text": "<p>this peace of code will help you </p>\n\n<pre><code> &lt;?php\n if (display_header_t...
2017/07/31
[ "https://wordpress.stackexchange.com/questions/275370", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124857/" ]
I'm trying to develop a theme. but "Display Site Title and Tagline" checkbox not working nothing change when i check or uncheck the site tile and tagline still exist. also the color option not giving any effect? please help my code for the header text is: ``` <header class="image-bg-fluid-height" id="startchange" style="background-image: url('<?php echo( get_header_image() ); ?>')" > <h1 class="h1-hdr"><?php bloginfo('name');?> </h1> <br/> <br/> <P id="header-pa"><?php bloginfo('description');?> </P> <a class="btn btn-primary btn-lg outline " role="button" href="#" id="btn-header">WATCH A VIDEO</a> <br/> <br/> </header> ```
this peace of code will help you ``` <?php if (display_header_text()==true){ echo '<h1>'.get_bloginfo( 'name' ) .'</h1>'; echo '<h2>'.get_bloginfo('description').'</h2>'; } else{ //do something } ?> ```
275,391
<p>I'm very new to word press having only installed it on the weekend, I'm fine with HTML &amp; CSS but PHP &amp; Wordpress is alien to me.</p> <p>I'm trying to display a post from a specific category that changes every day, i've searched everywhere and found the below code whihc works to a point.</p> <p>I just cant seem to get it to choose from a category number?</p> <p>Any help or explanation would be much appreciated.</p> <pre><code> &lt;?php if ( false === ( $totd_trans_post_id = get_transient( 'totd_trans_post_id' ) ) ) { $args = array('numberposts' =&gt; 1, 'orderby' =&gt; 'rand'); $totd = get_posts($args); $midnight = strtotime('midnight +1 day'); $timenow = time(); $timetillmidnight = $midnight - $timenow; echo $midnight; echo ",".$timenow; set_transient('totd_trans_post_id', $totd[0]-&gt;ID, $timetillmidnight); } else { $args = array('post__in' =&gt; array($totd_trans_post_id)); $totd = get_posts($args); } foreach( $totd as $post ) : setup_postdata($post); ?&gt; &lt;div&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;?php endforeach; ?&gt; </code></pre> <p><strong>EDIT</strong> Thanks for the suggestions but nothing seems to be working with my existing code, it still continues to pick a completey random post from all categories.</p>
[ { "answer_id": 275394, "author": "giolliano sulit", "author_id": 65984, "author_profile": "https://wordpress.stackexchange.com/users/65984", "pm_score": 1, "selected": false, "text": "<p>You can change your <code>get_posts $args</code></p>\n\n<p>Example:</p>\n\n<pre><code>$args = array(\...
2017/08/01
[ "https://wordpress.stackexchange.com/questions/275391", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/124991/" ]
I'm very new to word press having only installed it on the weekend, I'm fine with HTML & CSS but PHP & Wordpress is alien to me. I'm trying to display a post from a specific category that changes every day, i've searched everywhere and found the below code whihc works to a point. I just cant seem to get it to choose from a category number? Any help or explanation would be much appreciated. ``` <?php if ( false === ( $totd_trans_post_id = get_transient( 'totd_trans_post_id' ) ) ) { $args = array('numberposts' => 1, 'orderby' => 'rand'); $totd = get_posts($args); $midnight = strtotime('midnight +1 day'); $timenow = time(); $timetillmidnight = $midnight - $timenow; echo $midnight; echo ",".$timenow; set_transient('totd_trans_post_id', $totd[0]->ID, $timetillmidnight); } else { $args = array('post__in' => array($totd_trans_post_id)); $totd = get_posts($args); } foreach( $totd as $post ) : setup_postdata($post); ?> <div> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php the_content(); ?> </div> <?php endforeach; ?> ``` **EDIT** Thanks for the suggestions but nothing seems to be working with my existing code, it still continues to pick a completey random post from all categories.
You can change your `get_posts $args` Example: ``` $args = array( 'orderby' => 'rand', 'category_name' => 'your_category', 'showposts' => 1 ); ```
275,424
<pre><code> &lt;?php foreach($getPostCustom as $name=&gt;$value) { echo "&lt;strong&gt;".$name."&lt;/strong&gt;"." =&gt; "; foreach($value as $nameAr=&gt;$valueAr) { echo "&lt;br /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;"; echo $nameAr." =&gt; "; echo var_dump($valueAr); } echo "&lt;br /&gt;&lt;br /&gt;"; } ?&gt; </code></pre> <p>Actually I created a "Custom Post Type" and for that post type I added Custom Fields and Now I want to Display all my custom field values in the particular post type posts. The above Code displays all Custom Fields. Please help me to retrieve only custom fields of the particular Posts Only. Thanks In Advance..</p>
[ { "answer_id": 275430, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 0, "selected": false, "text": "<p>If you're in the <code>single_{$post_type_slug}</code> template . you can do this way:</p>...
2017/08/01
[ "https://wordpress.stackexchange.com/questions/275424", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/97802/" ]
``` <?php foreach($getPostCustom as $name=>$value) { echo "<strong>".$name."</strong>"." => "; foreach($value as $nameAr=>$valueAr) { echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; echo $nameAr." => "; echo var_dump($valueAr); } echo "<br /><br />"; } ?> ``` Actually I created a "Custom Post Type" and for that post type I added Custom Fields and Now I want to Display all my custom field values in the particular post type posts. The above Code displays all Custom Fields. Please help me to retrieve only custom fields of the particular Posts Only. Thanks In Advance..
``` <div class="col-xs-12 col-sm-12 col-md-8 col-lg-8 left_column"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h1> <?php the_title();?> </h1> <?php $post_meta = get_post_meta(get_the_ID()); foreach($post_meta as $key=>$value) { echo "<strong>".$key."</strong>"." => "; foreach($value as $nameAr=>$valueAr) { echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; echo $nameAr." => ".$valueAr; } echo "<br >"; } the_content(); endwhile; endif; ?> </div> ```
275,439
<p>Thanks in advance for all your help! </p> <p>I want to display posts (tours) that are in a specific location (city) so in my location_taxonomy.php I have a taxonomy query in the form of:</p> <pre><code>$args = array( 'post_type' =&gt; 'tour', 'meta_key' =&gt; 'trav_tour_city', 'meta_value' =&gt; $term-&gt;term_id, //city id ); </code></pre> <p>When the key stored in the tour has only one value (one city), it displays the posts. When the key has more than one value (multiple cities or id separated by commas), it doesn't.</p> <p>How can I change the $args so the query would determine that the current city ($term->term_id) exists within the comma separated values stored in 'trav_tour_city'?</p> <p>I have tried something in the line of:</p> <pre><code> // trying multiple cities $args = array( array( 'post_type' =&gt; 'tour', 'meta_key' =&gt; 'trav_tour_city', 'meta_query' =&gt; array( array( 'value' =&gt; $term-&gt;term_id, 'compare' =&gt; 'IN', ), ), ), ); </code></pre> <p>but obviously I don't know what I'm doing... haha.. </p> <p>Thanks guys... </p>
[ { "answer_id": 275430, "author": "Cesar Henrique Damascena", "author_id": 109804, "author_profile": "https://wordpress.stackexchange.com/users/109804", "pm_score": 0, "selected": false, "text": "<p>If you're in the <code>single_{$post_type_slug}</code> template . you can do this way:</p>...
2017/08/01
[ "https://wordpress.stackexchange.com/questions/275439", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125022/" ]
Thanks in advance for all your help! I want to display posts (tours) that are in a specific location (city) so in my location\_taxonomy.php I have a taxonomy query in the form of: ``` $args = array( 'post_type' => 'tour', 'meta_key' => 'trav_tour_city', 'meta_value' => $term->term_id, //city id ); ``` When the key stored in the tour has only one value (one city), it displays the posts. When the key has more than one value (multiple cities or id separated by commas), it doesn't. How can I change the $args so the query would determine that the current city ($term->term\_id) exists within the comma separated values stored in 'trav\_tour\_city'? I have tried something in the line of: ``` // trying multiple cities $args = array( array( 'post_type' => 'tour', 'meta_key' => 'trav_tour_city', 'meta_query' => array( array( 'value' => $term->term_id, 'compare' => 'IN', ), ), ), ); ``` but obviously I don't know what I'm doing... haha.. Thanks guys...
``` <div class="col-xs-12 col-sm-12 col-md-8 col-lg-8 left_column"> <?php if (have_posts()) : while (have_posts()) : the_post(); ?> <h1> <?php the_title();?> </h1> <?php $post_meta = get_post_meta(get_the_ID()); foreach($post_meta as $key=>$value) { echo "<strong>".$key."</strong>"." => "; foreach($value as $nameAr=>$valueAr) { echo "<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"; echo $nameAr." => ".$valueAr; } echo "<br >"; } the_content(); endwhile; endif; ?> </div> ```
275,445
<p>I am using <a href="https://wordpress.org/plugins/wck-custom-fields-and-custom-post-types-creator/" rel="nofollow noreferrer">this plugin</a> to create custom fields and custom post-types. I am able to create repeater custom fields in the following format.</p> <pre><code>1 Dummy Name1 Location1 2 Dummy Name2 Location2 ..... and so on </code></pre> <p>This field values are repeated and can be created n number of time. What I have trouble doing is this format</p> <pre><code>Session 2015-16 1 Dummy Name1 Location1 2 Dummy Name2 Location2 Session 2016-17 11 Dummy Name11 Location11 12 Dummy Name12 Location12 Session 2018-19 21 Dummy Name21 Location21 22 Dummy Name22 Location22 ..... and so on </code></pre> <p>Is it possible to create such format with the same plugin? If not how is it possible to create such layout.</p> <p>Thanks, Puneet</p>
[ { "answer_id": 275460, "author": "mrben522", "author_id": 84703, "author_profile": "https://wordpress.stackexchange.com/users/84703", "pm_score": 0, "selected": false, "text": "<p>I don't know about that plugin but I know you could easily do that with <a href=\"https://www.advancedcustom...
2017/08/01
[ "https://wordpress.stackexchange.com/questions/275445", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/99340/" ]
I am using [this plugin](https://wordpress.org/plugins/wck-custom-fields-and-custom-post-types-creator/) to create custom fields and custom post-types. I am able to create repeater custom fields in the following format. ``` 1 Dummy Name1 Location1 2 Dummy Name2 Location2 ..... and so on ``` This field values are repeated and can be created n number of time. What I have trouble doing is this format ``` Session 2015-16 1 Dummy Name1 Location1 2 Dummy Name2 Location2 Session 2016-17 11 Dummy Name11 Location11 12 Dummy Name12 Location12 Session 2018-19 21 Dummy Name21 Location21 22 Dummy Name22 Location22 ..... and so on ``` Is it possible to create such format with the same plugin? If not how is it possible to create such layout. Thanks, Puneet
I don't know about that plugin but I know you could easily do that with [ACF](https://www.advancedcustomfields.com/) repeater fields <https://www.advancedcustomfields.com/resources/repeater/>
275,485
<p>I am trying to use ACF Pro Select field to display a specify social media icons. So I have this code in my theme:</p> <pre><code>&lt;?php if( get_field('social_medias', 'option') == 'facebook' ): ?&gt; &lt;li&gt; &lt;a href="#"&gt; &lt;svg viewbox="0 0 6.5 14" xmlns="http://www.w3.org/2000/svg"&gt; &lt;path class="st0" d="M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z" id="Layer_3"&gt;&lt;/path&gt;&lt;/svg&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php endif; ?&gt; </code></pre> <p>"social_medias" is the SELECT field with several options, like Facebook or Twitter. What's wrong with this code? It's doesn't seems to works :D</p>
[ { "answer_id": 275486, "author": "Nuuu", "author_id": 124591, "author_profile": "https://wordpress.stackexchange.com/users/124591", "pm_score": 1, "selected": false, "text": "<p>I would do this instead:</p>\n\n<pre><code> &lt;?php\n if( have_rows('social_medias', 'option') ):\n ...
2017/08/01
[ "https://wordpress.stackexchange.com/questions/275485", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116847/" ]
I am trying to use ACF Pro Select field to display a specify social media icons. So I have this code in my theme: ``` <?php if( get_field('social_medias', 'option') == 'facebook' ): ?> <li> <a href="#"> <svg viewbox="0 0 6.5 14" xmlns="http://www.w3.org/2000/svg"> <path class="st0" d="M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z" id="Layer_3"></path></svg> </a> </li> <?php endif; ?> ``` "social\_medias" is the SELECT field with several options, like Facebook or Twitter. What's wrong with this code? It's doesn't seems to works :D
You can loop through your ACF options by using the code below. ``` <?php if( have_rows('social_medias', 'option') ): while ( have_rows('social_medias', 'option') ) : the_row(); $type = get_sub_field('type'); ?> <?php if ($type == "facebook") { ?> <li> <a href="#"> <svg viewbox="0 0 6.5 14" xmlns="http://www.w3.org/2000/svg"> <path class="st0" d="M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z" id="Layer_3"></path></svg> </a> </li> <?php } elseif ($type == "twitter") { ?> <li> <a href="#"> <svg viewbox="0 0 6.5 14" xmlns="http://www.w3.org/2000/svg"> <path class="st0" d="M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z" id="Layer_3"></path></svg> </a> </li> <?php } elseif ($type == "google") { ?> <li> <a href="#"> <svg viewbox="0 0 6.5 14" xmlns="http://www.w3.org/2000/svg"> <path class="st0" d="M1.4 14h2.9v-7h2l.2-2.5h-2.2v-1.4c0-.3.2-.6.5-.7h1.7000000000000002v-2.4h-2.2c-1.5-.1-2.8 1-2.9 2.5v2h-1.4v2.5h1.4v7z" id="Layer_3"></path></svg> </a> </li> <?php } endwhile; endif; ?> ```
275,491
<p>please help me: I need to get the parent of the current page, in other words: to get the parent of $direct_parent.Thanks!</p> <pre><code>&lt;?php global $post; $direct_parent = $post-&gt;post_parent; $parent = $direct_parent-&gt;post_parent; wp_list_pages( array( 'child_of' =&gt; $parent, 'title_li' =&gt; false, 'depth' =&gt; 1 ) ); ?&gt; </code></pre> <p>This code doesn't work(</p>
[ { "answer_id": 275492, "author": "Sabbir Hasan", "author_id": 76587, "author_profile": "https://wordpress.stackexchange.com/users/76587", "pm_score": 2, "selected": false, "text": "<p>Try using <strong>get_post_ancestors</strong>. Here is how you can apply this in your case:</p>\n\n<pre>...
2017/08/01
[ "https://wordpress.stackexchange.com/questions/275491", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/125046/" ]
please help me: I need to get the parent of the current page, in other words: to get the parent of $direct\_parent.Thanks! ``` <?php global $post; $direct_parent = $post->post_parent; $parent = $direct_parent->post_parent; wp_list_pages( array( 'child_of' => $parent, 'title_li' => false, 'depth' => 1 ) ); ?> ``` This code doesn't work(
Try using **get\_post\_ancestors**. Here is how you can apply this in your case: ``` <?php global $wp_query; $post = $wp_query->post; $ancestors = get_post_ancestors($post); if( empty($post->post_parent) ) { $parent = $post->ID; } else { $parent = end($ancestors); } if(wp_list_pages("title_li=&child_of=$parent&echo=0" )) { wp_list_pages("title_li=&child_of=$parent&depth=1" ); } ?> ``` You'll probably need to remove the depth parameters to show you're 3rd level pages. Let me know if this helps!